← Back to all snippets
PYTHON

Recursively Deep Merge Nested Dictionaries

Combine multiple nested Python dictionaries into one, intelligently merging sub-dictionaries to create unified configuration or data structures for web applications.

def deep_merge_dicts(dict1, dict2):
    merged_dict = dict1.copy()
    for key, value in dict2.items():
        if key in merged_dict and isinstance(merged_dict[key], dict) and isinstance(value, dict):
            merged_dict[key] = deep_merge_dicts(merged_dict[key], value)
        else:
            merged_dict[key] = value
    return merged_dict

# Base configuration
base_config = {
    "server": {"host": "localhost", "port": 8000},
    "database": {"type": "sqlite", "path": "app.db"},
    "logging": {"level": "INFO"}
}

# Environment-specific overrides
prod_config_override = {
    "server": {"host": "production.example.com"},
    "database": {"type": "postgresql", "host": "db.prod.example.com"},
    "logging": {"level": "ERROR", "file": "/var/log/app.log"}
}

# Merge configurations
final_config = deep_merge_dicts(base_config, prod_config_override)

# Result would be:
# {
#     'server': {'host': 'production.example.com', 'port': 8000},
#     'database': {'type': 'postgresql', 'path': 'app.db', 'host': 'db.prod.example.com'},
#     'logging': {'level': 'ERROR', 'file': '/var/log/app.log'}
# }
How it works: This snippet provides a utility function, `deep_merge_dicts`, to recursively combine two dictionaries. Unlike simple dictionary updates that overwrite entire nested dictionaries, this function intelligently merges them. If a key exists in both dictionaries and its values are both dictionaries, it calls itself recursively to merge those sub-dictionaries. Otherwise, it simply updates or adds the value from the second dictionary. This is highly valuable for managing configurations where default settings need to be overridden by environment-specific or user-defined parameters, preserving the structure of nested data in web applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs