Python: How to Iterate over Nested Dictionary -Dict of Dicts

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

To an infinite depth, a dictionary may include another dictionary, which can contain dictionaries, and so on. This is referred to as a nested dictionary.

Nested dictionaries are one among several ways during which structured information is represented (similar to records or structures in other languages).

Examples:

Input:

nesteddict = {
'hello': {'www': 100, 'yyy': 'Helloworld'},
'this': {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
'BTechGeeks': {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},

Output:

('hello', 'www', 100)
('hello', 'yyy', 'Helloworld')
('this', 'www', 'vikram')
('this', 'age', 20)
('this', 'DOB', 'FEB')
('BTechGeeks', 'PLACE', 'HYDERABAD')
('BTechGeeks', 'PINCODE', 500000)
('BTechGeeks', 'PYTHON', 'FUNCTIONS', 'Built in')
('BTechGeeks', 'PYTHON', 'year', 1999)

Traverse over Nested Dictionary

To get an iterable sequence of all key-value pairs in a normal dictionary, simply call the dictionary’s items() function. A value in a nested dictionary, on the other hand, can be another dictionary object. To accomplish this, we must call the items() function again on such values to obtain another iterable sequence of pairs and then search for dict objects within those pairs as well. Using recursion, we can accomplish all of this in a straightforward manner.

We wrote a function that takes a dictionary as an argument and returns all key-value pairs contained within it. Internal / nested dictionary values were included. It returns a tuple containing all keys for that value in hierarchy for nested structures.

Below is the implementation:

# function which print all the values of nested dictionary
def printNested(nesteddict):
    # Traverse the dictionary
    for key, value in nesteddict.items():
        # If the value is of the dictionary type, then print
        # all of the keys and values within the nested dictionary.
        if isinstance(value, dict):
            for pair in printNested(value):
                yield (key, *pair)
        else:
            yield(key, value)


# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
# passing nested dictionary to printNested Function using loop
for pair in printNested(nesteddict):
    print(pair)

Output:

('hello', 'www', 100)
('hello', 'yyy', 'Helloworld')
('this', 'www', 'vikram')
('this', 'age', 20)
('this', 'DOB', 'FEB')
('BTechGeeks', 'PLACE', 'HYDERABAD')
('BTechGeeks', 'PINCODE', 500000)
('BTechGeeks', 'PYTHON', 'FUNCTIONS', 'Built in')
('BTechGeeks', 'PYTHON', 'year', 1999)

Working of the above function:

We iterated over all the values in a dictionary of dictionaries using the function nested dict pair iterator() and printed each pair, including the parent keys.

We iterated over all the key-value pairs of a given dictionary object within the function, and for each value object in the pair, we checked whether the value is of dict type or not. If not, it just returns the pair, but if value is a dict, it calls itself again with the dict value object as an argument and returns all of its key-value pairs. The process is repeated until all of the internal dictionary objects have not been covered. This is how a dictionary of dictionaries’ key-value pairs are generated.
Related Programs: