There is a dictionary:

z = { 'a': 1, 's': [{'d': 2, 'f': 3}]} 

How to more elegantly refer to the nested dictionary without sharing the list?

my version -

  'for i in z['s'][0]['d']: if z['s'][0]['d'] == 'd': s + 1 

and considering that you need to check all the elements and the length of the branches you get 50 rows of nested loops

  • one
    In the sense of sharing? You called the appeal on the index? So, you can refer to the dictionary as follows: z['s'][0] , and then to the dictionary keys: z['s'][0]['d'] . - gil9red
  • mmm, I didn’t accurately formulate the question, the structure there is more complicated, two in each with three nested branches with an unknown number of final components, I would like to go through them in a cycle, but it turns out to be a mess. rather, something like this is passed to z = {'a': 1, 's': [{'d': [{'d': 2, 'f': 3}], 'f': [{'d': 2, 'f': 3}]}]} - djt111

1 answer 1

When you need to go through a complex multi-level structure in which the number of nesting levels is unknown, it is better to use recursion.

For example, we take the following structure:

 z = { 'a': 1, 's': [ { 'd': 2, 'f': 3 }, { 'd': 3, 'f': 3 }, { 'f': 3 } ], 'b': { 'd': 5, 'f': { 'd': 1, } } } 

And, for example, I came up with a task: calculate the sum of a value by key. In the data structure, I know that among containers there is only dict and list .

And according to the algorithm, we do the following: we check the current object, if it is a dictionary, we get a list of pairs for it - a key / value, and for a value we check what if it is a container, then we put this value into a function, otherwise we check it by key, if it matches - plus to the amount. If the current object is a list, then it cannot have a key, but among its values ​​there may be containers that we check in recursion:

 def get_sum_by_key(obj, key): val_sum = 0 if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, dict) or isinstance(v, list): val_sum += get_sum_by_key(v, key) else: if k == key: val_sum += v elif isinstance(obj, list): for v in obj: val_sum += get_sum_by_key(v, key) return val_sum print(get_sum_by_key(z, 'd')) # сумма 11 print(get_sum_by_key(z, 'f')) # сумма 9