Is there simple single line access to access each element of a nested dictionary in Python?

I often use nested dictionaries in Python 2.7 with 3 or more levels and use the nested loop structure, as shown below, to access each element. Does anyone know a simpler, faster or faster way to do this?

for foo in mydict:
    for bar in mydict[foo]:
        for etc in mydict[foo][bar]:
            mydict[foo][bar][etc] = "value"
+3
source share
2 answers

You use keys to access values. How about using dict.itervalues()instead?

for foo in mydict.itervalues():
    for bar in foo.itervalues():
        for etc in bar: # Iterating a dictionary yields keys
            bar[etc] = "value"
+3
source

Say you have the following dictionary:

mydict = {'a':{'aa':{'aaa':1}}, 'b':{'bb':{'bbb':2}}, 'c':{'cc':{'ccc':3}}}

The code published in your example will produce the following result:

{'a': {'aa': {'aaa': 'value'}}, 'c': {'cc': {'ccc': 'value'}},
 'b': {'bb': {'bbb': 'value'}}}

, , :

mydict = {key:{inner_key:{core_key:'value'
          for core_key in inner_dict.iterkeys()}
          for inner_key, inner_dict in value.iteritems()}
          for key, value in mydict.iteritems()}

, , . , .

+1

All Articles