← Back to Blog
Code Snippets August 3, 2026

Python: Deep Merge — Recursive Dictionary Merge with Strategy Control

💻 CODE SNIPPET — August 3, 2026

Python: Deep Merge — Recursive Dictionary Merge with Strategy Control

dict.update() and {a, b} flatten nested structures. Use deep_merge() instead:

def deep_merge(base, override, list_strategy='replace', skip_keys=None):
    result = base.copy()
    skip = skip_keys or set()
    for key, value in override.items():
        if key in skip:
            continue
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = deep_merge(result[key], value, list_strategy, skip)
        elif key in result and isinstance(result[key], list) and isinstance(value, list):
            if list_strategy == 'append':
                result[key] = result[key] + value
            elif list_strategy == 'prepend':
                result[key] = value + result[key]
            elif list_strategy == 'unique_append':
                result[key] = list(dict.fromkeys(result[key] + value))
            else:
                result[key] = value
        else:
            result[key] = value
    return result


4 list strategies:
  • replace (default) — override wins

  • append — concat override to base

  • prepend — concat base to override

  • unique_append — append, deduplicating


Pro tips:
  • Use skip_keys={'password', 'secret'} to protect sensitive config

  • Zero dependencies. Pure Python 3.10+.


When to use: Merging default config with environment overrides, combining API responses, or layering feature flags.