How would you efficiently merge two dictionaries in modern Python, and how do the different approaches handle overlapping keys?
Short answer
Python 3.9+ supports the merge operator (`|`) and update operator (`|=`), and dict unpacking (`{**a, **b}`) also works in earlier versions — in ALL cases, when both dictionaries share a key, the value from the SECOND (right-hand or later) dictionary wins, overwriting the first.
Advertisement
AModel answer
Python 3.9+ supports the merge operator (`|`) and update operator (`|=`), and dict unpacking (`{**a, **b}`) also works in earlier versions — in ALL cases, when both dictionaries share a key, the value from the SECOND (right-hand or later) dictionary wins, overwriting the first.
defaults = {"theme": "light", "retries": 3}
overrides = {"theme": "dark"}
merged = defaults | overrides # Python 3.9+: {'theme': 'dark', 'retries': 3}
merged2 = {**defaults, **overrides} # equivalent, works in older Python tooReal-world example
Merging a user's custom settings with a set of application defaults, letting the user's values take precedence.
Likely follow-ups
- How would you merge dictionaries where you need CUSTOM logic for handling conflicting keys, rather than simple overwrite?
Related topics