是否有一个简单的单行命令来访问Python中的嵌套字典的每个元素? [英] Is there a simple one-liner for accessing each element of a nested dictionary in Python?
本文介绍了是否有一个简单的单行命令来访问Python中的嵌套字典的每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
for mooict中的foo:
for bar在mydict [foo]:
for mydict [foo] [bar]:
mydict [foo] [bar] [etc] =value
解决方案
您正在使用键来存取值。如何使用 dict.itervalues()
而不是?
pre $ 用于mydict.itervalues()中的foo:
for bar in foo.itervalues():
等于bar:#迭代字典得到键
bar [etc] =value
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"
解决方案
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"
这篇关于是否有一个简单的单行命令来访问Python中的嵌套字典的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文