How do I merge two dictionaries in Python?
Short answer
On Python 3.9 and later use the pipe operator, or double-star unpacking on older versions. When keys collide, the value from the right-hand dictionary wins.
The short version
On Python 3.9 and later, combine two dictionaries with the | operator. On older versions, use {**a, **b}. In both cases, when the same key appears in both, the value from the second (right-hand) dictionary wins, which is the behaviour to remember.
The modern way
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
merged = a | b
print(merged) # {'x': 1, 'y': 3, 'z': 4}
Note y is 3, not 2: the right-hand dictionary overrode the left. This is a new merged dictionary; a and b are unchanged.
The way that works everywhere
Before Python 3.9, use double-star unpacking, which does the same thing.
merged = {**a, **b}
Merging in place
If you want to update an existing dictionary rather than create a new one, use update or the |= operator.
a.update(b) # a is now modified
a |= b # same effect on 3.9+
The difference matters: a | b leaves a alone, while a.update(b) changes a. Choose based on whether you want to keep the original.
The collision rule is the whole point
The one thing to internalise is which value survives a clash. In every form above, later wins. So a | b keeps b's values on overlap, and b | a keeps a's. If you actually want the first dictionary to take priority, simply swap the order.
b | a # {'y': 2, 'z': 4, 'x': 1} -> a's y wins now
Merging more than two
The operators chain, so you can fold several together, again with later winning.
c = {"w": 9}
a | b | c
Enjoying these?
Go from piecing together answers to real fluency.
Our courses take you from looking things up to doing the work with confidence, step by step on real data.
Browse the courses