Вопрос

I have a nested ordered dictionary field with the following value:

OrderedDict
([
 ('activateable', False),
 ('fields', 
    [OrderedDict ([ ('autoNumber', False),  ('name', ‘col_1’),  (‘amount’, ‘10’)]),
    [OrderedDict ([ ('autoNumber', False),  ('name', ‘col_2’),  (‘amount’, ‘10’)])
 )
 ('pin', False)
])

I want to pass the value col_1, col_2 and get the corresponding amount value. I’ve tried parsing by regular for loops and other iterations but couldn’t get it to the second level. Can you please suggest a method on how can I achieve this?

Это было полезно?

Решение

If I understand your question correctly, you're trying to access the amount value of the sub-dictionary that has name equal to some specified value (e.g. "col_1"). There's no direct way to find that without a loop, as you're searching for a value, not a key, but the code required shouldn't need to be terribly complicated:

for field in top_level_dict["fields"]:
    if field["name"] = "col_1":
        print(field["amount"])
        break

This prints the first match it finds (you can do whatever you want, rather than printing, that just seemed easiest for example code). If there is more than one sub-dict that can match and you want to print the "amount" values from all of them, you can take out the break statement.

If you have more than one value to search for, you might want to convert your data structure to something that can do more efficient lookups. For instance, here's some basic code to make a new dictionary that maps from your name values to the amount values (I'm assuming that all names are unique):

# set up a better mapping
name_amount_dict = {field["name"]: field["amount"] for field in top_level_dict["fields"]}

# use it to look up a value we want
print(name_amount_dict["col_1"])
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top