Menu Close

How to loop through all nested dictionary values with Python?

Sometimes, we want to loop through all nested dictionary values with Python.

In this article, we’ll look at how to loop through all nested dictionary values with Python.

How to loop through all nested dictionary values with Python?

To loop through all nested dictionary values with Python, we can create a recursive function.

For instance, we write

def my_print(d):
    for k, v in d.items():
        if isinstance(v, dict):
            my_print(v)
        else:
            print("{0} : {1}".format(k, v))

to create the my_print function that loops through key-value pairs in the d dict.

In the loop body, we use a for loop to loop through the k key and v value returned from items.

Then we call isinstance to check if v is a dict.

If it is, we call my_print with it.

Otherwise, we print the values of k and v.

Conclusion

To loop through all nested dictionary values with Python, we can create a recursive function.

Posted in Python, Python Answers