PYTHON

Recursively Deep Merge Python Dictionaries

Combine nested Python dictionaries deeply, ensuring all sub-dictionaries are merged, not overwritten. Crucial for managing complex configurations and data structures.

def deep_merge(dict1, dict2):
    """
    Recursively merges dict2 into dict1.
    Modifies dict1 in place and returns it.
    """
    for key, value in dict2.items():
        if key in dict1 and isinstance(dict1[key], dict) and isinstance(value, dict):
            # If both values are dictionaries, merge them recursively
            dict1[key] = deep_merge(dict1[key], value)
        else:
            # Otherwise, update or add the value from dict2
            dict1[key] = value
    return dict1

# Example Usage:
config1 = {
    'app_name': 'MyWebApp',
    'settings': {
        'debug': True,
        'database': {'host': 'localhost', 'port': 5432}
    },
    'features': ['auth', 'logging']
}

config2 = {
    'settings': {
        'debug': False, # Overwrite debug
        'database': {'port': 5433, 'user': 'admin'} # Merge database settings
    },
    'new_feature': True # Add new feature
}

merged_config = deep_merge(config1.copy(), config2)
print(f"Original Config 1:
{config1}
")
print(f"Config 2:
{config2}
")
print(f"Deep Merged Config:
{merged_config}")
How it works: This snippet provides a Python function `deep_merge` for recursively combining two dictionaries. Unlike the standard `dict.update()`, which would overwrite entire sub-dictionaries, `deep_merge` intelligently traverses both dictionaries. If a key exists in both and both values are dictionaries, it calls itself recursively to merge those sub-dictionaries. Otherwise, it simply updates or adds the value from the second dictionary into the first. This is invaluable in web development for scenarios like combining default configuration settings with user-specific overrides, where nested structures need to be preserved and updated granularly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs