Skip to main content
Dicts

How to merge two dicts in Python

Quick answer

Python 3.9+: use the | operator. {**a, **b} still works for older versions. Right-hand side wins on key conflicts.

a = {"x": 1, "y": 2}
b = {"y": 20, "z": 30}

merged = a | b
print(merged)  # {'x': 1, 'y': 20, 'z': 30}

The | operator (Python 3.9+) is the modern default: a | b returns a new dict combining both, with b's values winning on any key both share. It reads left-to-right like set union.

Before 3.9, {**a, **b} is the equivalent one-liner using dict unpacking. Both produce the SAME result and both create a NEW dict β€” neither mutates a or b.

To mutate a in place, use a.update(b) or a |= b (3.9+). Both add b's keys and overwrite conflicts, returning None.

Variations

Merge in place

a = {"x": 1}
a |= {"y": 2}
# or: a.update({"y": 2})
print(a)  # {'x': 1, 'y': 2}

Mutates a. |= is 3.9+; .update() works everywhere.

Merge with dict unpacking (pre-3.9)

merged = {**a, **b}

Same result as a | b, works on Python 3.5+.

Merge without overwriting

merged = {**b, **a}   # a wins now

Reverse the order so the earlier one takes precedence.

Practise this in your browser

Every how-to has a live lesson. Free tier, no card.

Start free β†’

Unlock every lesson

Pro β€” $12/mo, unlimited AI, cancel any time.

See Pro plans β†’

Get one Python lesson + one career idea every Friday

No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.

Related how-tos