迭代嵌套字典

时间:2016-09-07 08:42:11

标签: python python-3.x

目的这个代码可以迭代nested dictionary,但我正在寻找一个输出,它给出一个元组或list [键]然后[值]。这是代码:

from collections import Mapping, Set, Sequence

string_types = (str, unicode) if str is bytes else (str, bytes)
iteritems = lambda mapping: getattr(mapping, 'iteritems', mapping.items)()

def recurse(obj, path=(), memo=None):
    if memo is None:
        memo = set()
    iterator = None
    if isinstance(obj, Mapping):
        iterator = iteritems
    elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types):
        iterator = enumerate
    if iterator:
        if id(obj) not in memo:
            memo.add(id(obj))
            for path_component, value in iterator(obj):
                for result in recurse(value, path + (path_component,), memo):
                    yield result
            memo.remove(id(obj))
    else:
        yield path, obj


class addNestedDict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

loansDict=addNestedDict()
loansDict[15]['A']['B']=[1,2,3,4]

for k,v in recurse(loansDict):
    print(k,v)

我正在寻找的输出是一行(15 ,'A','B') [1,2,3,4],以便我能够引用k[0]k[1]v[0]等...

1 个答案:

答案 0 :(得分:1)

这似乎有效:

results = AddNestedDict()
for k,v in recurse(loansDict):
    results.setdefault(k[:-1], []).append(v)
result_key, result_value = results.items()[0]
print('{} {}'.format(result_key, result_value))  # -> (15, 'A', 'B') [1, 2, 3, 4]

我重命名了您的课程AddNestedDict,因此符合PEP 8指南。