How to merge two dictionaries in Python
· 2 min read · Updated March 16, 2026 · beginner
python dict dictionaries
The easiest way to merge two dictionaries depends on your Python version. Python 3.9+ has the cleanest syntax.
Using the | operator (Python 3.9+)
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
merged = a | b
print(merged) # {'x': 1, 'y': 3, 'z': 4}
The | operator keeps values from the second dict when keys overlap.
Using |= (Python 3.9+)
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
a |= b
print(a) # {'x': 1, 'y': 3, 'z': 4}
This merges directly into a without creating a new dictionary.
Using ** unpacking (Python 3.5+)
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
merged = {**a, **b}
print(merged) # {'x': 1, 'y': 3, 'z': 4}
Works in older Python versions but is slightly more verbose.
Using .update()
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
a.update(b)
print(a) # {'x': 1, 'y': 3, 'z': 4}
Mutates the original dictionary. Useful when you don’t need to keep the originals.
Merging multiple dictionaries
from collections import ChainMap
a = {"x": 1}
b = {"y": 2}
c = {"z": 3}
# ChainMap searches in order
result = dict(ChainMap(c, b, a))
print(result) # {'x': 1, 'y': 2, 'z': 3}
ChainMap is memory-efficient for large dictionaries since it doesn’t copy the data.