Merge Dictionaries with Update and Union
Core idea
When combining settings, decide which source wins for overlapping keys. For two dictionaries, base | overrides creates a new dictionary, with the right-hand values winning (Python 3.9+). base.update(overrides) instead changes base. Both approaches are shallow: nested values are not recursively merged or copied.
base = {"size": 10, "theme": "light"}overrides = {"theme": "dark"}merged = base | overridesprint(merged)print(base["theme"])The merged dictionary gets the custom theme, while base is unchanged.
Copy before update
base = {"limit": 4}merged = base.copy()merged.update({"limit": 8, "retry": 2})print(merged)print(base)A shallow copy followed by update also preserves the original top-level entries.
Nested value replacement
base = {"display": {"width": 80, "height": 40}}patch = {"display": {"width": 100}}print(base | patch)The entire display value is replaced; height is not automatically retained. Here the value is another dictionary.
Common mistake
Changing the order of the operands changes conflict precedence. A new top-level dictionary can still share nested mutable values with its inputs.
Practice
Merge two room configuration dictionaries with the second taking priority. Verify the original first dictionary still has its original values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dictionary merging
Check your understanding of dictionary merging.
What is printed?
print({"x": 2} | {"x": 5})What is printed?
a = {"x": 2}b = a | {"x": 5}print(a["x"])What is printed?
print({"a": {"x": 1}} | {"a": {"y": 3}})Which approach preserves the original top-level entries?