Python: Iterate/Loop over all nested dictionary values

In this article, we will discuss different ways to iterate over all values of a nested dictionary.

Nested dictionary is a dictionary of dictionaries. It is a kind of dictionary which has another dictionary objects as values in the key-value pairs. These dictionary values can also have another dictionaries internally. The nested structure of dictionary can go on and on.

For example,

# A Nested dictionary i.e. dictionaty of dictionaries
students = {
            'ID 1':    {'Name': 'Shaun', 'Age': 35, 'City': 'Delhi'},
            'ID 2':    {'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai'},
            'ID 3':    {'Name': 'Smriti', 'Age': 33, 'City': 'Sydney'},
            'ID 4':    {'Name': 'Jacob', 'Age': 23, 'City': {'perm': 'Tokyo',
                                                             'current': 'London'}},
            }

Now we want to iterate over all values of this dictionary i.e. including the values of internal dictionaries too. The expected result is like,

Shaun
35
Delhi
Ritika
31
Mumbai
Smriti
33
Sydney
Jacob
23
Tokyo
London

Let’s see how to do that.

Iterate over all values of a nested dictionary in python

For a normal dictionary, we can just call the values() function of dictionary to get an iterable sequence of values. But in a nested dictionary a value can be an another dictionary object. For that we need to again call the values() function and get another iterable sequence of values and then look for dict objects in those values too. We can achieve this in a simple manner using reccursion.

We have created a function that accepts a dictionary as an argument and yields all values in it. Included the values of internal / nested dictionaries. For this it uses the recursion. Let’s use this function to iterate over all values of a dictionary of dictionaries,

# A Nested dictionary i.e. dictionaty of dictionaries
students = {
            'ID 1':    {'Name': 'Shaun', 'Age': 35, 'City': 'Delhi'},
            'ID 2':    {'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai'},
            'ID 3':    {'Name': 'Smriti', 'Age': 33, 'City': 'Sydney'},
            'ID 4':    {'Name': 'Jacob', 'Age': 23, 'City': {'perm': 'Tokyo',
                                                             'current': 'London'}},
            }


def nested_dict_values_iterator(dict_obj):
    ''' This function accepts a nested dictionary as argument
        and iterate over all values of nested dictionaries
    '''
    # Iterate over all values of given dictionary
    for value in dict_obj.values():
        # Check if value is of dict type
        if isinstance(value, dict):
            # If value is dict then iterate over all its values
            for v in  nested_dict_values_iterator(value):
                yield v
        else:
            # If value is not dict type then yield the value
            yield value


#Loop through all nested dictionary values
for value in nested_dict_values_iterator(students):
    print(value)

Output:

Shaun
35
Delhi
Ritika
31
Mumbai
Smriti
33
Sydney
Jacob
23
Tokyo
London

Using the function nested_dict_values_iterator() we iterated over all the values of a dictionary of dictionaries and printed each value.

How it works ?

Inside the function, we iterated over all the values of a given dictionary object and for each value it checks if the value is of dict type or not. If not then it just yields the value, but if value is dict type then it reccusrively calls itself with the dict value object as argument and then yields all its values. The process goes on and on, till all the internal dictionary objects are not covered. This is how it yields all the values of a dictionary of dictionaries.

Get a list of all values of nested dictionary in python

We can also create a list of all values of a dictionary of dictionaries, by passing the yielded values from function nested_dict_values_iterator() to the list(). For example,

# A Nested dictionary i.e. dictionaty of dictionaries
students = {
            'ID 1':    {'Name': 'Shaun', 'Age': 35, 'City': 'Delhi'},
            'ID 2':    {'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai'},
            'ID 3':    {'Name': 'Smriti', 'Age': 33, 'City': 'Sydney'},
            'ID 4':    {'Name': 'Jacob', 'Age': 23, 'City': {'perm': 'Tokyo',
                                                             'current': 'London'}},
            }


def nested_dict_values_iterator(dict_obj):
    ''' This function accepts a nested dictionary as argument
        and iterate over all values of nested dictionaries
    '''
    # Iterate over all values of given dictionary
    for value in dict_obj.values():
        # Check if value is of dict type
        if isinstance(value, dict):
            # If value is dict then iterate over all its values
            for v in  nested_dict_values_iterator(value):
                yield v
        else:
            # If value is not dict type then yield the value
            yield value


# Get list of all values of nested dictionary
all_values = list(nested_dict_values_iterator(students))

print(all_values)

Output:

['Shaun', 35, 'Delhi', 'Ritika', 31, 'Mumbai', 'Smriti', 33, 'Sydney', 'Jacob', 23, 'Tokyo', 'London']

Summary:

In this article we learned how to iterate over all values of a nested dictionary object i.e. a dictionary of dictionaries.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top