如何分解嵌套字典以进行赋值迭代

u59ebvdq  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(396)

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

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
vbopmzt1

vbopmzt11#

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 .

相关问题