close

How to iterate through a nested dict?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to iterate through a nested dict in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to iterate through a nested dict?

  1. How to iterate through a nested dict?

    In place of iteritems() you can use items() as well, but iteritems() is much more efficient and returns an iterator.

  2. iterate through a nested dict

    In place of iteritems() you can use items() as well, but iteritems() is much more efficient and returns an iterator.

Method 1

keys() method returns a view object that displays a list of all the keys in the dictionary

Iterate nested dictionary:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

for i in d.keys():
    print i
    for j in d[i].keys():
        print j

OR

for i in d:
    print i
    for j in d[i]:
        print j

output:

dict1 
foo
bar

dict2
baz 
quux

where i iterate main dictionary key and j iterate the nested dictionary key.

Method 2

As the requested output, the code goes like this

    d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

    for k1,v1 in d.iteritems(): # the basic way
        temp = ""   
        temp+=k1
        for k2,v2 in v1.iteritems():
           temp = temp+" "+str(k2)+" "+str(v2)
        print temp

In place of iteritems() you can use items() as well, but iteritems() is much more efficient and returns an iterator.

Hope this helps 🙂

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read