Is there an easy way of iterating over nested dictionary, which may consist of other objects like lists, tuples, then again dictionaries so that iteration covers all the elements of these other objects?
For example, if I type a key of a nested dictionary object, I would get it all listed in the Python interpreter.
[edit] here is example dictionary:
{
'key_1': 'value_1',
'key_2': {'key_21': [(2100, 2101), (2110, 2111)],
'key_22': ['l1', 'l2'],
'key_23': {'key_231': 'v'},
'key_24': {'key_241': 502,
'key_242': [(5, 0), (7, 0)],
'key_243': {'key_2431': [0, 0],
'key_2432': 504,
'key_2433': [(11451, 0), (11452, 0)]
},
'key_244': {'key_2441': {'key_24411': {'key_244111': 'v_24411',
'key_244112': [(5549, 0)]
},
'key_24412':'v_24412'
},
'key_2441': ['ll1', 'll2']
}
},
}
}
sorry for being unreadable, but I did the best that I could.
just write d. items() , it will work, by default on iterating the name of dict returns only the keys.
One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.
To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
def recurse(d):
if type(d)==type({}):
for k in d:
recurse(d[k])
else:
print d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With