Get all keys of a nested dictionary [duplicate]

In other answers, you were pointed to how to solve your task for given dicts, with maximum depth level equaling to two. Here is the program that will alows you to loop through key-value pair of a dict with unlimited number of nesting levels (more generic approach):

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            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

1 2
3 4
5 6

That is relevant if you are interested only in key-value pair on deepest level (when value is not dict). If you are also interested in key-value pair where value is dict, make a small edit:

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

Leave a Comment