Introduction: Nested Dictionaries in Python
Nested dictionaries in Python are dictionaries that contain other dictionaries as values. In simple terms, a value inside a dictionary can itself be another dictionary, allowing you to build multi-level or hierarchical data structures.
They are commonly used when working with structured data such as JSON responses, configuration files, or real-world records where information is grouped in multiple layers.
This makes it easier to organize related data in a clean and logical way, especially when handling complex datasets.
Example of Python nested dictionary:
nested_dict = {
"person1": {
"name": "Alice",
"age": 25
},
"person2": {
"name": "Bob",
"age": 30
}
}Explanation: “person1” and “person2” are keys in the outer dictionary. Each key contains another dictionary holding details like name and age.
This structure helps store related information in a clear hierarchical format.
Tip: Before working with nested structures, make sure you understand the basics covered in our Python Dictionary complete introduction.
Syntax, Structure and Examples: Nested Dictionaries in Python
Syntax
Now that the concept is clear, here is the standard syntax used to create Python nested dictionaries.
nested_dict = {
"key1": {
"subkey1": value1,
"subkey2": value2
},
"key2": {
"subkey3": value3,
"subkey4": value4
}
}
Structure Elements in Nested Dictionaries
The following table explains the main components used in a nested dictionary structure.
| Element | Description | Type |
|---|---|---|
| key (outer dictionary) | The main key used in the outer dictionary to store a nested dictionary | str, int, etc. |
| nested dictionary | A dictionary stored as a value inside another dictionary | dict |
| subkey (inner dictionary) | The key inside the nested dictionary used to store specific values | str, int, etc. |
| value | The actual data stored inside the inner dictionary | Any |
Now that you understand the main components of a nested dictionary, let’s see how nested dictionaries are created, accessed, modified, and traversed in practical scenarios.
Examples of Python Nested Dictionaries
Let’s go through some common examples of Python nested dictionaries to understand how they are created and used in real situations.
Example 1: Creating a Simple Nested Dictionary
employee = {
"name": "Alice",
"details": {
"age": 28,
"department": "HR",
"location": "New York"
}
}
print(employee)
# Output:
{'name': 'Alice', 'details': {'age': 28, 'department': 'HR', 'location': 'New York'}}
Explanation: The employee dictionary contains a nested dictionary called details, which stores related attributes in a structured format.
Example 2: Accessing Nested Dictionary Values
employee = {
"name": "Alice",
"details": {
"age": 28,
"department": "HR",
"location": "New York"
}
}
print(employee["details"]["department"])
# Output:
HR
Explanation: Nested values are accessed using chained keys, where “details” is the outer key and “department” is the inner key.
Example 3: Updating Nested Dictionary Values
employee = {
"name": "Alice",
"details": {
"age": 28,
"department": "HR",
"location": "New York"
}
}
employee["details"]["location"] = "San Francisco"
print(employee["details"]["location"])
# Output:
San Francisco
Explanation: The nested value is updated using chained assignment, modifying only the targeted key.
Example 4: Adding a New Nested Key-Value Pair
employee = {
"name": "Alice",
"details": {
"age": 28,
"department": "HR",
"location": "New York"
}
}
employee["details"]["email"] = "alice@example.com"
print(employee["details"])
# Output:
{'age': 28, 'department': 'HR', 'location': 'New York', 'email': 'alice@example.com'}
Explanation: A new key-value pair is added dynamically inside the nested dictionary without changing the existing structure.
Example 5: Iterating Through Nested Dictionary
employee = {
"name": "Alice",
"details": {
"age": 28,
"department": "HR",
"location": "New York"
}
}
for key, subdict in employee.items():
if isinstance(subdict, dict):
for subkey, value in subdict.items():
print(f"{subkey}: {value}")
else:
print(f"{key}: {subdict}")
# Output:
name: Alice
age: 28
department: HR
location: New York
Explanation: The outer dictionary is first traversed using items(). When a nested dictionary is encountered, a second loop iterates through its key-value pairs, allowing data from multiple levels to be accessed.
Example 6: Nested Dictionaries with Multiple Layers
company = {
"employee1": {
"name": "Bob",
"details": {"age": 34, "department": "IT"}
},
"employee2": {
"name": "Eve",
"details": {"age": 29, "department": "Marketing"}
}
}
print(company["employee1"]["details"]["department"])
# Output:
IT
Explanation: Here we access deeper values by chaining keys step by step, which allows retrieval of data stored at multiple levels in a structured way.
Advantages of Python Nested Dictionaries
Nested dictionaries offer several advantages when working with structured or multi-level data in Python applications. Below are some of the key advantages of using nested dictionaries:
- Organize related data in a structured format
- Improve readability for hierarchical information
- Make JSON-like data easier to manage
- Allow flexible multi-level data storage
- Simplify access and management of deeply related information
Use Cases: When and Why to Use Nested Dictionaries
Here are some common real-world use cases where nested dictionaries in Python are most useful:
- Represent JSON-like data efficiently.
- Store configuration settings with multiple levels.
- Group related entities like employees and their attributes.
- Handle multi-level categorization in web apps and data systems.
Advantages of Python Nested Dictionaries
Nested dictionaries in Python offer several advantages when working with structured or multi-level data in Python applications. Below are some of its important advantages:
- Organize related data in a structured format
- Improve readability for hierarchical information
- Make JSON-like data easier to manage
- Allow flexible multi-level data storage
- Simplify access and management of deeply related information
Key Takeaways: Nested Dictionaries
Here is a quick summary of the most important points about nested dictionaries in Python:
- Nested dictionaries store dictionaries inside dictionaries.
- They are ideal for JSON data, configurations, and hierarchical information.
- They support creation, access, updates, additions, and iteration.
- They allow multiple layers of data using simple key chaining.
- They are widely used in real-world Python applications for structured data handling.