PYTHON

Recursively Merge Two Dictionaries for Configuration Overrides

Learn to perform a deep merge of two Python dictionaries, essential for combining default settings with user-specific configurations in web applications.

def deep_merge_dicts(source, destination):
    """
    Recursively merges two dictionaries.
    Entries from 'source' will overwrite entries in 'destination'
    if they are not dictionaries themselves. If both are dictionaries,
    they are merged recursively.
    """
    for key, value in source.items():
        if key in destination and isinstance(destination[key], dict) and isinstance(value, dict):
            destination[key] = deep_merge_dicts(value, destination[key])
        else:
            destination[key] = value
    return destination

# Example Usage
defaults = {
    "app_name": "MyWebApp",
    "database": {
        "host": "localhost",
        "port": 5432,
        "user": "root"
    },
    "logging": {
        "level": "INFO",
        "file": "/var/log/app.log"
    }
}

user_settings = {
    "database": {
        "host": "db.example.com",
        "port": 3306 # new port
    },
    "logging": {
        "level": "DEBUG" # override level
    },
    "new_feature": { # add new feature config
        "enabled": True
    }
}

merged_config = deep_merge_dicts(user_settings, defaults.copy()) # .copy() to avoid modifying defaults
print(merged_config)
How it works: This snippet provides a recursive function `deep_merge_dicts` to combine two dictionaries. It's particularly useful in web development for managing configuration settings where you have a set of default values that need to be overridden or extended by user-specific or environment-specific settings. The function iterates through the source dictionary and, if a key exists in both dictionaries and both values are dictionaries, it merges them recursively. Otherwise, the source value overwrites or adds to the destination dictionary.

Need help integrating this into your project?

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

Hire DigitalCodeLabs