How to iterate through a nested dict?

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 :)


The following will work with multiple levels of nested-dictionary:

def get_all_keys(d):
    for key, value in d.items():
        yield key
        if isinstance(value, dict):
            yield from get_all_keys(value)


d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'dict3': {'baz': 3, 'quux': 4}}}
for x in get_all_keys(d):
    print(x)

This will give you:

dict1
foo
bar
dict2
dict3
baz
quux

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.