How to recursively iterate a nested Python dictionary?


Given below is a nested directory object

D1={1: {2: {3: 4, 5: 6}, 3: {4: 5, 6: 7}}, 2: {3: {4: 5}, 4: {6: 7}}}

Example

Following recursive function is called repetitively if the value component of each item in directory is a directory itself.

def iterdict(d):
  for k,v in d.items():        
     if isinstance(v, dict):
         iterdict(v)
     else:            
         print (k,":",v)

iterdict(D1)

Output

When the initial dictionary object is passed to this function, all the key-value pairs are traversed. The output is:

3 4
5 6
4 5
6 7
4 5
6 7

Updated on: 17-Dec-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements