Loop through all nested dictionary values?

前端 未结 12 1437
温柔的废话
温柔的废话 2020-11-22 09:16
for k, v in d.iteritems():
    if type(v) is dict:
        for t, c in v.iteritems():
            print \"{0} : {1}\".format(t, c)

I\'m trying to l

12条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 09:44

    Here is pythonic way to do it. This function will allow you to loop through key-value pair in all the levels. It does not save the whole thing to the memory but rather walks through the dict as you loop through it

    def recursive_items(dictionary):
        for key, value in dictionary.items():
            if type(value) is dict:
                yield (key, value)
                yield from recursive_items(value)
            else:
                yield (key, value)
    
    a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}
    
    for key, value in recursive_items(a):
        print(key, value)
    

    Prints

    a {1: {1: 2, 3: 4}, 2: {5: 6}}
    1 {1: 2, 3: 4}
    1 2
    3 4
    2 {5: 6}
    5 6
    

提交回复
热议问题