What are the modern ways to merge two dictionaries in Python, and how do they handle overlapping keys?
Answer
Python 3.9 added the `|` merge operator and the `|=` in-place merge operator for dicts, giving a concise `merged = defaults | overrides` that returns a new dict. Older idioms include `{**defaults, **overrides}` unpacking and `defaults.copy(); result.update(overrides)`. In every case, when both dictionaries define the same key, the value from the right-hand or later-applied dictionary wins.
Strong answer includes
- | and |= merge operators since 3.9
- double-star unpacking as the older equivalent
- right-hand or later dict's value wins on key collision
Practical example
config = defaults | user_overridesproduces a new dict where any key present in both takes the value from `user_overrides` .