Categories
Python Answers

How to loop through all nested dictionary values with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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