PYTHON

Deep Merge Multiple Python Dictionaries

Combine multiple Python dictionaries recursively, handling nested dictionaries without overwriting inner structures, perfect for merging configuration objects or data payloads.

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

config1 = {
    "database": {"host": "localhost", "port": 5432},
    "app": {"debug": True, "timeout": 30},
    "users": ["admin", "guest"]
}

config2 = {
    "database": {"port": 5433, "user": "root"},
    "app": {"timeout": 60, "env": "production"},
    "logging": {"level": "INFO"}
}

config3 = {
    "database": {"host": "remote.db"},
    "app": {"debug": False}
}

# Merge config1 and config2
merged_config = deep_merge(config1, config2)
print("Merged config1 and config2:
", merged_config)

# Merge all three
final_config = deep_merge(deep_merge(config1, config2), config3)
print("
Final merged config:
", final_config)

# Expected Output:
# Merged config1 and config2:
#  {'database': {'host': 'localhost', 'port': 5433, 'user': 'root'}, 'app': {'debug': True, 'timeout': 60, 'env': 'production'}, 'users': ['admin', 'guest'], 'logging': {'level': 'INFO'}}
# 
# Final merged config:
#  {'database': {'host': 'remote.db', 'port': 5433, 'user': 'root'}, 'app': {'debug': False, 'timeout': 60, 'env': 'production'}, 'users': ['admin', 'guest'], 'logging': {'level': 'INFO'}}
How it works: Standard dictionary merging (`dict.update()` or `**` operator) performs a shallow merge, overwriting entire nested dictionaries. This `deep_merge` function provides a recursive solution. It iterates through the second dictionary (`dict2`) and for each key, if both `dict1` and `dict2` contain that key and their values are dictionaries, it recursively calls `deep_merge`. Otherwise, it simply updates or adds the value from `dict2`. This ensures that nested structures are combined intelligently rather than being completely replaced.

Need help integrating this into your project?

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

Hire DigitalCodeLabs