Deep Merge Dicts Recursive

Recursively merge nested dictionaries with conflict resolution for config composition.

PythonData Integrity

Code

pythonsnippet
14 lines
def deep_merge(base, override):
    result = base.copy()
    for key, value in override.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = deep_merge(result[key], value)
        else:
            result[key] = value
    return result

def merge_configs(*configs):
    merged = {}
    for config in configs:
        merged = deep_merge(merged, config)
    return merged

How the snippet works

Count the functions deep_merge and merge_configs as the entire surface area of Deep Merge Dicts Recursive.

Repetition is confined to for key, value in override.items() — the rest of the file is straight-line.

Using it

Signature: def deep_merge(base, override)

deep_merge is the public entry point; everything else in the file exists to support it.

Key statements

def deep_merge(base, override):
    result = base.copy()
    for key, value in override.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = deep_merge(result[key], value)
        else:
            result[key] = value
    return result
def merge_configs(*configs):
    merged = {}
    for config in configs:
        merged = deep_merge(merged, config)
    return merged

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `deep_merge`, `merge_configs` at load time.