How to recursively iterate a nested Python dictionary?

PythonServer Side ProgrammingProgramming

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
raja
Published on 29-Dec-2017 13:59:27
Advertisements