How to iterate over nested dictionary in Python

In this post, we are going to learn how to iterate over a nested dictionary in python using for loop with dictionary items() method. A nested dictionary is a dictionary of dictionaries. Whenever we have multiple dictionaries inside a single dictionary then it makes it a nested dictionary.

1. How to iterate over nested dictionary in Python Using for loop


The dictionary method items() are used to iterate over each key and value in the dictionary. In this example, we have a nested dictionary. The step to loop through the nested dictionary

  • The first loop we are using to print the name of the nested dictionary
  • The second loop is to iterate over the key-value pair of the dictionary nested dictionary
  • The print statement is to print nested dictionary.
data_dict ={'Record1':{'Name': 'Jack','Mark': 100, 'Subject': 'Math'},
 'Record2':{ 'Name': 'Rack', 'Mark': 100,'Subject:':'Math'},
'Record3':{ 'Name': 'Max','Mark': 100, 'Subject': 'Music'},
'Record4':{ 'Name': 'David', 'Mark':100,'Subject': 'Math'}
 
}


for key, value in data_dict.items():
    print('\n',key+':\n')
    for key, value in value.items():
        print('{} : {}'.format(key, value))

Output

 Record1:

Name : Jack
Mark : 100
Subject : Math

 Record2:

Name : Rack
Mark : 100
Subject: : Math

 Record3:

Name : Max
Mark : 100
Subject : Music

 Record4:

Name : David
Mark : 100
Subject : Math

2. Custom function to iterate over nested dictionary in Python


In this example, we have defined a custom function iterate_nest_Dict() that takes a nested dictionary as an argument and iterates over the key-value pair using the dictionary items() method.

  • The instance() is used to check if the given input is a dictionary.
    • When it is a dictionary custom function iterate_nest_Dict() calls recursively along with for loop to iterate over dictionary and return
    • When it is not a dictionary simply key-value pair is return.
data_dict ={'Record1':{'Name': 'Jack','Mark': 100, 'Subject': 'Math'},
 'Record2':{ 'Name': 'Rack', 'Mark': 100,'Subject:':'Math'},
'Record3':{ 'Name': 'Max','Mark': 100, 'Subject': 'Music'},
'Record4':{ 'Name': 'David', 'Mark':100,'Subject': 'Math'}
 
}



def iterate_nest_Dict(data_dict):
    
   
    for key, value in data_dict.items():
        
        if isinstance(value, dict):
           
            for key_value in  iterate_nest_Dict(value):
                yield (key, *key_value)
        else:
          
            yield (key, value)

for key_value in iterate_nest_Dict(data_dict):
    print(key_value)




Output

('Record1', 'Name', 'Jack')
('Record1', 'Mark', 100)
('Record1', 'Subject', 'Math')
('Record2', 'Name', 'Rack')
('Record2', 'Mark', 100)
('Record2', 'Subject:', 'Math')
('Record3', 'Name', 'Max')
('Record3', 'Mark', 100)
('Record3', 'Subject', 'Music')
('Record4', 'Name', 'David')
('Record4', 'Mark', 100)
('Record4', 'Subject', 'Math')

3. Get all the values in nested dictionary using loop


In this python program example, we will understand how to loop through all nested dictionary values using fro loop. We have defined a custom function name nested_dict_Values() that takes a nested dictionary as an argument. The steps we are following the custom function

  • The for loop is iterating over the values of the nested dictionary by using dictionary function values().
    • In the next step on each iteration, we are checking the type of value.When it is dictionary call the custom function recursivley.
    • whenenver it is not dictionary we are return the values from dictionary.
  • Calling the nested_dict_Values() function and converting all the values in dictionary as list by using list() method
data_dict ={'Record1':{'Name': 'Jack','Mark': 100, 'Subject': 'Math'},
 'Record2':{ 'Name': 'Rack', 'Mark': 100,'Subject:':'Math'},
'Record3':{ 'Name': 'Max','Mark': 100, 'Subject': 'Music'},
'Record4':{ 'Name': 'David', 'Mark':100,'Subject': 'Math'}
 
}


def nested_dict_Values(data_dict ):           

  for val in data_dict.values():
    if isinstance(val, dict):
      yield from nested_dict_Values(val)
    else:
      yield val


print(list(nested_dict_Values(data_dict)))

Output

['Jack', 100, 'Math', 'Rack', 100, 'Math', 'Max', 100, 'Music', 'David', 100, 'Math']

4. Loop through list of dictionaries in Python


In this example, we are looping through the list of dictionaries by simply using nested for loop. The first loop is to iterate over the list of dictionaries and the second for loop is to iterate over the key-value pair in each dictionary and we are printing the key-value pair using the print statement.

list_of_dicts = [{'Name': 'Jack','Mark': 100, 'Subject': 'Math'}, { 'Name': 'Rack', 'Mark': 100,'Subject:':'Math'},
            { 'Name': 'Max','Mark': 100, 'Subject': 'Music'}]

for dic in list_of_dicts:
    for key,val in dic.items():
        print(f'{key}: {val}')

Output

Name: Jack
Mark: 100
Subject: Math
Name: Rack
Mark: 100
Subject:: Math
Name: Max
Mark: 100
Subject: Music

Summary

In this post, we have learned How to iterate over a nested dictionary in Python with examples.