🐍
Code Snippet — August 3, 2026Python: Deep Merge — Recursive Dict Merge with Strategy Control
dict.update() and
{a, b} flatten nested dicts. This gives you
recursive merge,
4 list strategies,
skip_keys for protected config,
type coercion,
custom conflict resolvers, and a
diff() change preview. Zero deps.
from copy import deepcopy
def deep_merge(base, override, strategy="recursive",
list_strategy="replace", skip_keys=None,
type_coerce=False, on_conflict=None):
result = deepcopy(base)
for key, ov in override.items():
if key in (skip_keys or set()): continue
if key not in result:
result[key] = ov; continue
bv = result[key]
if on_conflict: result[key] = on_conflict(key, bv, ov); continue
if isinstance(bv, dict) and isinstance(ov, dict):
if strategy == "recursive":
result[key] = deep_merge(bv, ov, strategy,
list_strategy, skip_keys, type_coerce, on_conflict)
else: result[key] = deepcopy(ov)
elif isinstance(bv, list) and isinstance(ov, list):
if list_strategy == "append": result[key] = bv + ov
elif list_strategy == "prepend": result[key] = ov + bv
elif list_strategy == "unique_append":
result[key] = bv + [x for x in ov if x not in bv]
else: result[key] = ov
else: result[key] = ov
return result
base = {"db": {"host": "localhost", "port": 5432}}
ovr = {"db": {"host": "prod.db", "pool_size": 20}}
config = deep_merge(base, ovr)
# → {"db": {"host": "prod.db", "port": 5432, "pool_size": 20}}
# Protect secrets, append lists, coerce strings
deep_merge(a, b, skip_keys={"secret"}, list_strategy="append", type_coerce=True)
💡 Drop in config.py for layered config & env overrides. Full version w/ 10 self-tests in today's workspace.