Open In App

How to Loop Three Level Nested Python Dictionary

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given a three level nested Python Dictionary and our task is to loop through that three level nested Python dictionary. In this article, we will explore two different approaches Nested for loops and Recursion to Loop 3 Level Nested Dictionary Python.

Loop Three Level Nested Dictionary Python

Below are the possible approaches to Loop 3 Level Nested Dictionary in Python.

  • Using Nested for Loops
  • Using Recursion

Loop 3 Level Nested Dictionary Using Nested for Loops

In this approach, we are using nested for loops to iterate through each level of the 3-level nested dictionary. The outermost loop (for key1, value1 in dict.items()) iterates over the first level, the middle loop (for key2, value2 in value1.items()) iterates over the second level, and the innermost loop (for key3, value3 in value2.items()) iterates over the third level.

Python3




dict = {
    'Geeks': {
        'for': {
            'Geeks': 1,
            'CS': 2,
            'IT': 3
        },
        'GFG': {
            'Courses': {
                'DSA': 4,
                'Algorithms': 5
            },
            'Quiz': 6
        }
    }
}
for key1, value1 in dict.items():
    print(f"Level 1: {key1}")
    for key2, value2 in value1.items():
        print(f"\tLevel 2: {key2}")
        for key3, value3 in value2.items():
            print(f"\t\tLevel 3: {key3} - {value3}")


Output

Level 1: Geeks
    Level 2: for
        Level 3: Geeks - 1
        Level 3: CS - 2
        Level 3: IT - 3
    Level 2: GFG
        Level 3: Courses - {'DSA': 4, 'Algorithms': 5}
        Level 3: Quiz - 6



Loop 3 Level Nested Dictionary Using Recursion

In this approach, we are using recursion to traverse and print each level of the 3-level nested dictionary. The recursiveFn function iterates through the key-value pairs, printing the current key with appropriate indentation based on the level. If the value is a nested dictionary, the function is called recursively with an incremented level. The base case is when the level is 3, at which point the entire dictionary content at that level is printed as a single entry.

Python3




def recursiveFn(d, level=1):
    for key, value in d.items():
        print('\t' * (level - 1) + f'Level {level}: {key}', end=' ')
        if isinstance(value, dict):
            print()
            if level == 3:
                print('\t' * level + f'- {value}')
            else:
                recursiveFn(value, level + 1)
        else:
            print(f'- {value}')
dict_data = {
    'Geeks': {
        'for': {
            'Geeks': 1,
            'CS': 2,
            'IT': 3
        },
        'GFG': {
            'Courses': {
                'DSA': 4,
                'Algorithms': 5
            },
            'Quiz': 6
        }
    }
}
recursiveFn(dict_data)


Output

Level 1: Geeks 
    Level 2: for 
        Level 3: Geeks - 1
        Level 3: CS - 2
        Level 3: IT - 3
    Level 2: GFG 
        Level 3: Courses 
            - {'DSA': 4, 'Algorithms': 5}
        Level 3: Quiz - 6




Previous Article
Next Article

Similar Reads

Three Level Nested Dictionary Python
In Python, a dictionary is a built-in data type used to store data in key-value pairs. Defined with curly braces `{}`, each pair is separated by a colon `:`. This allows for efficient representation and easy access to data, making it a versatile tool for organizing information. What is 3 Level Nested Dictionary?A 3-level nested dictionary refers to
4 min read
Loop Through a Nested Dictionary in Python
Working with nested dictionaries in Python can be a common scenario, especially when dealing with complex data structures. Iterating through a nested dictionary efficiently is crucial for extracting and manipulating the desired information. In this article, we will explore five simple and generally used methods to loop through a nested dictionary i
3 min read
Python - Get particular Nested level Items from Dictionary
Given a dictionary, extract items from a particular level. Examples: Input : {"Gfg" : { "n1": 3, "nd2": { "n2" : 6 }}, "is" : { "ne1": 5, "ndi2": { "ne2" : 8, "ne22" : 10 } }}, K = 2 Output : {'n2': 6, 'ne2': 8, 'ne22': 10} Explanation : 2nd nesting items are extracted. Input : {"Gfg" : { "n1": 3, "nd2": { "n2" : 6 }}, "is" : { "ne1": 5, "ndi2": {
4 min read
Define a 3 Level Nested Dictionary in Python
In Python, dictionaries provide a versatile way to store and organize data. Nested dictionaries, in particular, allow for the creation of multi-level structures. In this article, we'll explore the process of defining a 3-level nested dictionary and demonstrate various methods to achieve this. Define a 3-Level Nested Dictionary in PythonBelow are so
3 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
3 Level Nested Dictionary To Multiindex Pandas Dataframe
Pandas is a powerful data manipulation and analysis library for Python. One of its key features is the ability to handle hierarchical indexing, also known as MultiIndexing. This allows you to work with more complex, multi-dimensional data in a structured way. In this article, we will explore how to convert a nested dictionary into a Pandas DataFram
3 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Convert a nested for loop to a map equivalent in Python
In this article, let us see how to convert a nested for loop to a map equivalent in python. A nested for loop's map equivalent does the same job as the for loop but in a single line. A map equivalent is more efficient than that of a nested for loop. A for loop can be stopped intermittently but the map function cannot be stopped in between. Syntax:
3 min read
Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
4 min read