Python – How to Iterate over nested dictionary ?
Last Updated :
28 Feb, 2023
In this article, we will discuss how to iterate over a nested dictionary in Python.
Nested dictionary means dictionary inside a dictionary and we are going to see every possible way of iterating over such a data structure.
Nested dictionary in use:
{‘Student 1’: {‘Name’: ‘Bobby’, ‘Id’: 1, ‘Age’: 20},
‘Student 2’: {‘Name’: ‘ojaswi’, ‘Id’: 2, ‘Age’: 22},
‘Student 3’: {‘Name’: ‘rohith’, ‘Id’: 3, ‘Age’: 20}}
For this we will use for loop to iterate through a dictionary to get the all the key , values of nested dictionaries.
Syntax:
for i in dictionary_name:
print(dictionary_name[i])
where
- dictionary_name is the input dictionary
- dictionary_name[i] is the value to get dictionaries
Example: Python program to get the nested dictionaries from a dictionary
Python3
data = {
'Student 1' : { 'Name' : 'Bobby' , 'Id' : 1 , "Age" : 20 },
'Student 2' : { 'Name' : 'ojaswi' , 'Id' : 2 , "Age" : 22 },
'Student 3' : { 'Name' : 'rohith' , 'Id' : 3 , "Age" : 20 },
}
for i in data:
print (data[i])
|
Output:
{'Name': 'Bobby', 'Id': 1, 'Age': 20}
{'Name': 'ojaswi', 'Id': 2, 'Age': 22}
{'Name': 'rohith', 'Id': 3, 'Age': 20}
Time complexity : O(n)
Space complexity : O(n)
It is also possible to get only either keys or values if the that is what the requirement asks for. Again for this for loop is employed with a little variation.
To get keys from the nested dictionary for each iteration keys() function is called.
Syntax:
data[i].keys()
Example: Python program to get keys from the nested dictionary
Python3
data = {
'Student 1' : { 'Name' : 'Bobby' , 'Id' : 1 , "Age" : 20 },
'Student 2' : { 'Name' : 'ojaswi' , 'Id' : 2 , "Age" : 22 },
'Student 3' : { 'Name' : 'rohith' , 'Id' : 3 , "Age" : 20 },
}
for i in data:
print (data[i].keys())
|
Output:
dict_values(['Name', Id, Age])
dict_values(['Name', Id, Age])
dict_values(['Name', Id, Age])
Time complexity : O(n)
Space complexity : O(n)
Similarly to get values, after each iteration values() function is used to get the job done.
Syntax:
data[i].values()
Example: Python program to get values from the nested dictionary
Python3
data = {
'Student 1' : { 'Name' : 'Bobby' , 'Id' : 1 , "Age" : 20 },
'Student 2' : { 'Name' : 'ojaswi' , 'Id' : 2 , "Age" : 22 },
'Student 3' : { 'Name' : 'rohith' , 'Id' : 3 , "Age" : 20 },
}
for i in data:
print (data[i].values())
|
Output:
dict_values(['Bobby', 1, 20])
dict_values(['ojaswi', 2, 22])
dict_values(['rohith', 3, 20])
Time complexity : O(n)
Space complexity : O(n)
Please Login to comment...