PYTHON

Deep Merge Nested Dictionaries

Learn to recursively merge two or more Python dictionaries, handling nested structures and overwriting values intelligently for flexible configuration or data processing needs.

def deep_merge(dict1, dict2):
    """Recursively merges dict2 into dict1, handling nested dictionaries."""
    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

# Example Usage:
config1 = {
    "database": {"host": "localhost", "port": 5432},
    "app": {"debug": True, "timeout": 30}
}

config2 = {
    "database": {"user": "admin", "port": 5433}, # Port will be overwritten
    "app": {"timeout": 60, "name": "MyWebApp"} # timeout overwritten, name added
}

config3 = {
    "app": {"debug": False}
}

merged_config = deep_merge(config1, config2)
merged_config = deep_merge(merged_config, config3)

# print(merged_config)
# Expected output:
# {"database": {"host": "localhost", "port": 5433, "user": "admin"}, 
#  "app": {"debug": False, "timeout": 60, "name": "MyWebApp"}}
How it works: This function `deep_merge` takes two dictionaries and recursively merges the second into the first. If a key exists in both dictionaries and its values are themselves dictionaries, the function calls itself to merge those nested dictionaries. Otherwise, the value from the second dictionary overwrites the value from the first. This is crucial for managing configurations, combining user preferences, or processing API data where nested structures need careful handling without flattening.

Need help integrating this into your project?

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

Hire DigitalCodeLabs