💻
Code Snippet — July 27, 2026Deep Merge Nested Dicts with Conflict Resolution (Python)
dict.update() silently replaces nested dicts. This recursive merge supports conflict strategies, list handling, and
None-skipping:
from copy import deepcopy
def deep_merge(base, override, strategy="override",
list_strategy="replace", skip_none=True):
"""Recursively merge nested dicts."""
result = deepcopy(base)
for key, new_val in override.items():
if skip_none and new_val is None:
continue
if key not in result:
result[key] = deepcopy(new_val)
continue
old_val = result[key]
if isinstance(old_val, dict) and isinstance(new_val, dict):
result[key] = deep_merge(old_val, new_val, strategy, list_strategy, skip_none)
continue
if isinstance(old_val, list) and isinstance(new_val, list):
if list_strategy == "replace":
result[key] = deepcopy(new_val)
elif list_strategy == "append":
result[key] = old_val + deepcopy(new_val)
elif list_strategy == "union":
seen, merged = set(), []
for i in old_val + new_val:
h = str(i) if isinstance(i, (dict, list)) else i
if h not in seen: seen.add(h); merged.append(i)
result[key] = merged
continue
if strategy == "override": result[key] = deepcopy(new_val)
elif strategy == "error": raise ValueError(f"Conflict at {key}")
return result
Usage: reduce(deep_merge, [defaults, env, user])💡
3 conflict strategies (override/preserve/error), 3 list modes (replace/append/union). skip_none=True → None means "don't touch". Zero deps, Python 3.8+.