Three Level Nested Dictionary Python
Last Updated :
30 Jan, 2024
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': '[email protected]'
}
}
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: [email protected]
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': '[email protected]', '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': '[email protected]', '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.
Similar Reads
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
3 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
3 min read
Python - How to Iterate over nested dictionary ? 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}
3 min read
Sort a Nested Dictionary by Value in Python Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 min read
Convert Nested Dictionary to List in Python In this article, weâll explore several methods to Convert Nested Dictionaries to a List in Python. List comprehension is the fastest and most concise way to convert a nested dictionary into a list.Pythona = { "a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}, } # Convert nested dictionary to a list of li
3 min read