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
z['s'][0], and then to the dictionary keys:z['s'][0]['d']. - gil9red