PYTHON

Recursively Merge Nested Python Dictionaries

Discover how to perform a deep merge on two nested Python dictionaries, preserving existing keys and recursively updating values, crucial for complex configuration management.

def deep_merge(dict1, dict2):
    """
    Recursively merges dict2 into dict1. Values from dict2
    overwrite values from dict1. If both are dictionaries,
    they are merged recursively.
    """
    merged = dict1.copy() # Start with a copy to avoid modifying original dict1

    for key, value in dict2.items():
        if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
            # If both values are dictionaries, merge them recursively
            merged[key] = deep_merge(merged[key], value)
        else:
            # Otherwise, overwrite or add the value
            merged[key] = value
    return merged

# Example Usage
config_base = {
    'app': {'name': 'WebApp', 'version': '1.0'},
    'database': {'host': 'localhost', 'port': 5432},
    'features': ['auth', 'logging']
}

config_override = {
    'app': {'version': '1.1', 'debug': True},
    'database': {'port': 5433, 'user': 'admin'},
    'new_setting': True
}

merged_config = deep_merge(config_base, config_override)
print(f"Deep Merged Config:
{merged_config}")

# Expected output:
# {
#     'app': {'name': 'WebApp', 'version': '1.1', 'debug': True},
#     'database': {'host': 'localhost', 'port': 5433, 'user': 'admin'},
#     'features': ['auth', 'logging'],
#     'new_setting': True
# }
How it works: This snippet provides a function `deep_merge` to recursively combine two nested dictionaries. It iterates through the second dictionary, `dict2`. If a key exists in both dictionaries and both corresponding values are themselves dictionaries, the function calls itself recursively to merge those nested dictionaries. Otherwise, values from `dict2` simply overwrite or add to `dict1`, ensuring a thorough, deep merge suitable for complex configurations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs