PYTHON
Deep Merge Nested Dictionaries for Configuration Management
Learn to deep merge Python dictionaries, combining nested structures effectively. Ideal for overriding default configurations with user-specific settings in web projects.
def deep_merge(dict1, dict2):
"""
Recursively merges dict2 into dict1.
Modifies dict1 in place.
"""
for key, value in dict2.items():
if key in dict1 and isinstance(dict1[key], dict) and isinstance(value, dict):
deep_merge(dict1[key], value)
else:
dict1[key] = value
return dict1
# Default configuration
default_config = {
'database': {
'host': 'localhost',
'port': 5432,
'user': 'admin'
},
'logging': {
'level': 'INFO',
'file': '/var/log/app.log'
},
'server': {
'port': 8000
}
}
# User-specific or environment-specific overrides
user_config = {
'database': {
'host': 'db.example.com',
'port': 1234 # Override port
},
'logging': {
'level': 'DEBUG' # Override log level
},
'server': {
'threads': 4 # Add new key
}
}
# Merge user_config into default_config
merged_config = deep_merge(default_config.copy(), user_config)
print(f"Default config: {default_config}")
print(f"User config: {user_config}")
print(f"Merged config: {merged_config}")
# Expected merged_config:
# {
# 'database': {'host': 'db.example.com', 'port': 1234, 'user': 'admin'},
# 'logging': {'level': 'DEBUG', 'file': '/var/log/app.log'},
# 'server': {'port': 8000, 'threads': 4}
# }
How it works: While Python's dictionary union operator (`|` in Python 3.9+) or `update()` method performs a shallow merge, deep merging is crucial for nested data structures like configuration settings. This snippet defines a `deep_merge` function that recursively traverses both dictionaries. If a key exists in both and its values are dictionaries, it recursively merges them. Otherwise, it simply updates the value, allowing for granular overrides of nested settings without losing sibling keys.