How do you merge dictionaries, and what about deep merges?
AdvancedConceptLanguage essentials & functions
Answer
Shallow merge: merged = base | override (3.9+) or {**base, **override}; base |= override updates in place. Right-hand values win.
These replace nested dicts wholesale. For layered config (defaults, then environment, then CLI flags) you need a recursive merge:
def deep_merge(a: dict, b: dict) -> dict:
out = dict(a)
for k, v in b.items():
out[k] = deep_merge(out[k], v) if isinstance(out.get(k), dict) and isinstance(v, dict) else v
return out
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner