Open In App

Python – How to Iterate over nested dictionary ?

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# create a nested dictionary with 3
# fields of 3 students
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},
}
 
 
# iterate all the nested dictionaries with
# both keys and values
for i in data:
    
    # display
    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




# create a nested dictionary with 3 fields of 3 students
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},
}
 
 
# iterate all the nested dictionaries with keys
for i in data:
  # display
    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




# create a nested dictionary with 3 fields of 3 students
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},
}
 
 
# iterate all the nested dictionaries with values
for i in data:
  # display
    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)



Previous Article
Next Article

Similar Reads

Python - Iterate over Tuples in Dictionary
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print(dictionary_name[index][i] Example: Python Code #
2 min read
Iterate over a dictionary in Python
In this article, we will cover How to Iterate Through a Dictionary in Python. Dictionary in Python is a collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair in Python. To Iterate through values in a dictionary you can use built-in m
6 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Iterate over a set in Python
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variat
6 min read
Iterate over characters of a string in Python
In Python, while operating with String, one can do multiple operations on it. Let's see how to iterate over the characters of a string in Python. Example #1: Using simple iteration and range() C/C++ Code # Python program to iterate over characters of a string # Code #1 string_name = "geeksforgeeks" # Iterate over the string for el
3 min read
Iterate over words of a String in Python
Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string. Examples: Input: str = "GeeksforGeeks is a computer science portal for Geeks" Output: GeeksforGeeks is a computer science portal for Geeks Input: str = "Geeks for Geeks" Output: Geeks for Geeks Method 1: Using split() Using
4 min read
Python - Iterate over Columns in NumPy
Numpy (abbreviation for 'Numerical Python') is a library for performing large-scale mathematical operations in a fast and efficient manner. This article serves to educate you about methods one could use to iterate over columns in an 2D NumPy array. Since a single-dimensional array only consists of linear elements, there doesn't exists a distinguish
3 min read
How to Iterate over Dataframe Groups in Python-Pandas?
In this article, we'll see how we can iterate over the groups in which a data frame is divided. So, let's see different ways to do this task. First, Let's create a data frame: C/C++ Code # import pandas library import pandas as pd # dictionary dict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframe df = pd.DataFrame(dict) # show
2 min read
three90RightbarBannerImg