Is there a simple one-liner for accessing each element of a nested dictionary in Python?

夙愿已清 提交于 2019-12-23 21:09:54

问题


I often use nested dictionaries in Python 2.7 with 3 or more tiers and use a nested for loop structure, as shown below, to access each element. does anyone know of a simpler, neater or faster method to do so?

for foo in mydict:
    for bar in mydict[foo]:
        for etc in mydict[foo][bar]:
            mydict[foo][bar][etc] = "value"

回答1:


You're using 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"



回答2:


Let's say you have the following dictionary:

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

The code you posted in your example will produce the following result:

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

Since your question also mentions a one liner you could use a nested dictionary comprehension but it is not necessarily faster nor neater:

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()}

This will produce the same result as the code you posted.It is technically a one-liner even though for the sake of readability it should not be written in one line.



来源:https://stackoverflow.com/questions/22787366/is-there-a-simple-one-liner-for-accessing-each-element-of-a-nested-dictionary-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!