如何为赋值迭代分解嵌套字典



我有字典,我必须像这样迭代:

for akey,bdict in cdict.items():
for dkey,edict in bdict.items():
for fkey,gdict in edict.items():
for hkey,ival in gdict.items():
# do something

我如何定义explode,以便用任意大的嵌套dict做这样的事情(我可能需要在一些迭代项周围使用括号,但括号的使用将由explode决定,我想(?

for akey,dkey,fkey,hkey,ival in explode(cdict):
# do something
# or 
for *keys,val in explode(any_nesteddict):
# do something

在7月9日23:38 popcornddude回复后更新

有没有一种方法可以在字典中解压缩到某个级别?例如,如果我想获得akeydkeyedict

for (akey,dkey),edict in explode(cdict, level=2):
# do stuff
# which is different from original question:
for (akey,dkey,fkey,hkey),ival in explode(cdict):
# do stuff
def explode(dct):
# iterate over the top-level dictionary
k, v in dct.items():
if isinstance(v, dict):
# it's a nested dictionary, so recurse
for ks, v2 in explode(v):
# ks is a tuple of keys, and we want to
# prepend k, so we convert it into a tuple
yield (k,)+ks, v2
else:
# make sure that in the base case
# we're still yielding the keys as a tuple
yield (k,), v

我们需要写(k,)而不仅仅是(k),因为Python中的元组是用逗号定义的,括号只是用来分组的,所以(k) == k,但(k,)是一个包含k的元组。

相关内容

  • 没有找到相关文章

最新更新