Open In App

Three Level Nested Dictionary Python

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 a dictionary structure in which there are three levels of nesting. In Python, a dictionary is a collection of key-value pairs, and it can contain other dictionaries as values. When you have a dictionary within another dictionary, and then another dictionary within the inner dictionary, you have a 3-level nested dictionary.

Example :

nested_dict = {
'first_level_key': {
'second_level_key': {
'third_level_key': 'value'
}
}
}

3 Level Nested Dictionary in Python

Below, are the ways to create 3 Level Nested Dictionary in Python.

3 Level Nested Dictionary Python Direct Initialization

In this example, below code initializes a three-level nested dictionary with a key-value pair at the third level. The print(nested_dict) statement displays the entire nested dictionary structure.

Python3




nested_dict = {
    'first_level_key': {
        'second_level_key': {
            'third_level_key': 'value'
        }
    }
}
print(nested_dict)


Output

{'first_level_key': {'second_level_key': {'third_level_key': 'value'}}}

3 Level Nested Dictionary Python Using dict() constructor

In this example, below code initializes a three-level nested dictionary using the dict() constructor and then prints the entire nested dictionary structure.

Python3




nested_dict = dict(
    first_level_key=dict(
        second_level_key=dict(
            third_level_key='value'
        )
    )
)
print(nested_dict)


Output

{'first_level_key': {'second_level_key': {'third_level_key': 'value'}}}

3 Level Nested Dictionary Python Iterative Approach

In this example, below code dynamically creates a nested dictionary with the specified levels and assigns the final key-value pair. It then prints the resulting nested dictionary.

Python3




nested_dict = {}
levels = ['first_level_key', 'second_level_key', 'third_level_key']
 
current_dict = nested_dict
for level in levels:
    current_dict[level] = {}
    current_dict = current_dict[level]
 
current_dict['final_key'] = 'value'
print(nested_dict)


Output :

{'first_level_key': {'second_level_key': {'third_level_key': {'final_key': 'value'}}}}

Wokring with 3 Level Nested Dictionary Python

Here, we will explain how we can access, add, update and delete the element from 3 Level Nested Dictionary Python.

  • Access Element
  • Add Element
  • Update Element
  • Delete Element

Create 3 Level Dictionary

In this code, contact_details dictionary contains information about a person, including their name, phone numbers for home and work, and an email address.

Python3




contact_details = {
    'person_id': {
        'name': 'John Doe',
        'phone': {
            'home': '123-456-7890',
            'work': '987-654-3210'
        },
        'email': 'john.doe@example.com'
    }
}


Access Element

In this example, below code accesses and prints specific information from the nested `contact_details` dictionary, extracting the person’s name, home phone number, and email address.

Python3




# Accessing elements
person_name = contact_details['person_id']['name']
home_phone = contact_details['person_id']['phone']['home']
email = contact_details['person_id']['email']
 
print(f"Name: {person_name}")
print(f"Home Phone: {home_phone}")
print(f"Email: {email}\n")


Output

Name: John Doe
Home Phone: 123-456-7890
Email: john.doe@example.com

Add Element

In this example, below code adds an ‘address’ element to the existing contact_details dictionary under the ‘person_id’, including the ‘city’ and ‘zipcode’. The updated dictionary is then printed

Python3




# Adding elements
contact_details['person_id']['address'] = {'city': 'Anytown', 'zipcode': '12345'}
print("After Adding Address:")
print(contact_details, "\n")


Output :

After Adding Address:
{'person_id': {'name': 'John Doe', 'phone': {'home': '123-456-7890', 'work': '987-654-3210'},
'email': 'john.doe@example.com', 'address': {'city': 'Anytown', 'zipcode': '12345'}}}

Update Element

In this example, below code updates the ‘work’ phone number in the existing contact_details dictionary under the ‘person_id’. The modified dictionary is then printed.

Python3




# Updating elements
contact_details['person_id']['phone']['work'] = '999-888-7777'
print("After Updating Work Phone:")
print(contact_details, "\n")


Output

After Updating Work Phone:
{'person_id': {'name': 'John Doe', 'phone': {'home': '123-456-7890', 'work': '999-888-7777'},
'email': 'john.doe@example.com', 'address': {'city': 'Anytown', 'zipcode': '12345'}}}

Delete Element

In this example, below code deletes the ’email’ element from the existing contact_details dictionary under ‘person_id’. The updated dictionary is then printed.

Python3




# Deleting elements
del contact_details['person_id']['email']
print("After Deleting Email:")
print(contact_details)


Output

After Deleting Email:
{'person_id': {'name': 'John Doe', 'phone': {'home': '123-456-7890', 'work': '999-888-7777'},
'address': {'city': 'Anytown', 'zipcode': '12345'}}}

Conclusion

Nesting dictionaries are powerful for organizing information into hierarchical layers, creating a structured and easily navigable system. This capability proves invaluable when dealing with intricate data, such as organizing student grades within classes, or organizing classes within a school. The flexibility and clarity provided by nested dictionaries enhance the readability and maintainability of code, making it easier for developers to represent real-world relationships in their programs.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads