【问题标题】:how do I explode a nested dictionary for assignment iteration如何分解嵌套字典以进行赋值迭代
【发布时间】:2021-09-20 03:55:01
【问题描述】:

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

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,以便我可以使用任意大的嵌套字典来做这样的事情(我可能需要在一些迭代项周围加上括号,但括号的使用将由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 popcorndude 回答后更新

有没有办法在字典中解压到某个级别,例如,如果我想得到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

【问题讨论】:

标签: python loops dictionary nested


【解决方案1】:
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的元组.

【讨论】:

  • 谢谢!我已经用后续问题更新了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
  • 1970-01-01
  • 2014-01-21
  • 2019-11-26
  • 1970-01-01
相关资源
最近更新 更多