In Python, you can merge two dictionaries in several ways, depending on your Python version and whether you want to modify the original dictionaries or create a new one. Here are the most common methods:
1. Using the |
Operator (Python 3.9+)
The simplest and most modern approach:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = dict1 | dict2 # New dict (original dicts unchanged)
print(merged) # Output: {'a': 1, 'b': 3, 'c': 4}
- Overlapping keys: Values from
dict2
override those indict1
. - Non-destructive: Creates a new dictionary.
2. Using **
Unpacking (Python 3.5+)
Merge dictionaries in a single expression:
merged = {**dict1, **dict2} # Same result as above
- Works for merging multiple dictionaries:
merged = {**dict1, **dict2, **dict3}
3. Using update()
(In-Place Modification)
Modify dict1
to include dict2
‘s key-value pairs:
dict1.update(dict2) # Updates dict1 in-place
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}
- Destructive: Overwrites
dict1
. - To preserve originals, create a copy first:
merged = dict1.copy()
merged.update(dict2)
4. Using collections.ChainMap
(Non-Destructive View)
Group dictionaries without merging (access keys as a single view):
from collections import ChainMap
merged_view = ChainMap(dict1, dict2)
print(merged_view['b']) # Output: 2 (first occurrence)
- No new dict: Acts as a read-only view.
- Changes to
dict1
ordict2
reflect inmerged_view
.
Key Differences
Method | Python Version | Creates New Dict? | Modifies Original? | Overwrites Keys? |
---|---|---|---|---|
| Operator | 3.9+ | ✅ Yes | ❌ No | ✅ Yes (last) |
** Unpacking | 3.5+ | ✅ Yes | ❌ No | ✅ Yes (last) |
update() | All | ❌ No | ✅ Yes | ✅ Yes (last) |
ChainMap | All | ❌ No (view) | ❌ No | ❌ No (first) |
Recommendation
- Python 3.9+: Use
|
for clarity. - Python 3.5–3.8: Use
**
unpacking. - Legacy Code: Use
update()
with a copy (e.g.,merged = dict1.copy(); merged.update(dict2)
).
For handling large dictionaries or performance-critical code, test the methods to compare efficiency. Always ensure you’re aware of key-overwrite behavior!