Working with Nested Dictionaries in Python: Access, Modify, and Iterate
Nested dictionaries provide a way to organize hierarchical data in Python. This structure consists of dictionaries within dictionaries, creating a multi-level data model similar to tree structures.
Creating a Nested Dictionary
data = {
'employee_a': {'name': 'Alice', 'department': 'Engineering', 'salary': 75000},
'employee_b': {'name': 'Bob', 'department': 'Marketing', 'salary': 65000}
}
This structure holds employee records where each employee has multiple attributes stored as an inner dicsionary.
Accessing Values in Nested Dictionaries
Direct Access with Multiple Indices
Chain the key lookups to reach deep values:
data = {
'employee_a': {'name': 'Alice', 'department': 'Engineering'},
'employee_b': {'name': 'Bob', 'department': 'Marketing'}
}
dept = data['employee_a']['department']
print(dept) # Engineering
Safe Access with get() Method
Avoid KeyError exceptions when keys might not exist:
data = {
'employee_a': {'name': 'Alice', 'department': 'Engineering'}
}
# Retrieve nested value with fallback
email = data.get('employee_c', {}).get('email', 'Not Available')
print(email) # Not Available
# Alternative using try-except
try:
result = data['employee_a']['title']
except KeyError:
result = 'No title'
Modifying Nested Dictionaries
Updating Existing Values
data = {
'employee_a': {'name': 'Alice', 'salary': 75000},
'employee_b': {'name': 'Bob', 'salary': 65000}
}
data['employee_a']['salary'] = 80000
data['employee_b']['department'] = 'Sales'
Adding New Entries
data = {
'employee_a': {'name': 'Alice'},
'employee_b': {'name': 'Bob'}
}
data['employee_c'] = {'name': 'Charlie', 'department': 'HR', 'salary': 60000}
data['employee_a']['level'] = 'Senior'
Removing Data from Nested Dictionaries
Deleting Specific Keys
data = {
'employee_a': {'name': 'Alice', 'age': 30, 'city': 'NYC'},
'employee_b': {'name': 'Bob', 'age': 25}
}
del data['employee_a']['city']
print(data['employee_a']) # {'name': 'Alice', 'age': 30}
Removing Entire Entries
data = {
'employee_a': {'name': 'Alice'},
'employee_b': {'name': 'Bob'}
}
del data['employee_a']
Clearing All Data
data = {
'employee_a': {'name': 'Alice'},
'employee_b': {'name': 'Bob'}
}
data.clear()
Iterating Through Nested Dictionaries
Using Nested Loops
data = {
'employee_a': {'name': 'Alice', 'department': 'Engineering'},
'employee_b': {'name': 'Bob', 'department': 'Marketing'}
}
for emp_id, details in data.items():
print(f"Employee ID: {emp_id}")
for attribute, value in details.items():
print(f" {attribute}: {value}")
Iterating Keys and Values Separately
data = {
'employee_a': {'name': 'Alice', 'department': 'Engineering'},
'employee_b': {'name': 'Bob', 'department': 'Marketing'}
}
# Iterate over top-level keys
for emp_id in data.keys():
print(f"ID: {emp_id}")
# Iterate over inner dictionary values
for details in data.values():
print(details.get('name'))
Flattening Nested Dictionaries
data = {
'employee_a': {'name': 'Alice', 'department': 'Engineering'},
'employee_b': {'name': 'Bob', 'department': 'Marketing'}
}
flattened = {
f"{emp_id}_{attr}": value
for emp_id, details in data.items()
for attr, value in details.items()
}
# {'employee_a_name': 'Alice', 'employee_a_department': 'Engineering', ...}
Recursive Access Helper Function
For deeply nested structures, a helper function simplifies access:
def get_nested(data, path, default=None):
"""Access nested dictionary values using a path list."""
current = data
for key in path:
if isinstance(current, dict) and key in current:
current = current[key]
else:
return default
return current
data = {
'company': {
'department': {
'team': {'lead': 'Alice'}
}
}
}
lead = get_nested(data, ['company', 'department', 'team', 'lead'])
print(lead) # Alice
Practical Use Cases
Configuration Management
config = {
'development': {
'database': {'host': 'localhost', 'port': 5432},
'cache': {'enabled': True, 'ttl': 3600}
},
'production': {
'database': {'host': 'prod-db.example.com', 'port': 5432},
'cache': {'enabled': True, 'ttl': 7200}
}
}
env = 'development'
db_host = config[env]['database']['host']
Tree-Style Data Structures
filesystem = {
'/': {
'home': {
'user': {
'documents': {'report.pdf': {'size': 1024}},
'images': {}
}
}
}
}