merge

dict1 | dict2

Merge operator (Python 3.9+) that returns a new dict containing the entries of d1 followed by d2, with d2's values winning on shared keys. Both operands must be dicts; neither is mutated.

d1 | d2

Parameters

Parameter Purpose
left operand Base dict — its keys come first in insertion order
right operand Overriding dict — its values win on shared keys
returns New dict; originals unchanged

Examples

>>> {'a': 1, 'b': 2} | {'b': 99, 'c': 3}
{'a': 1, 'b': 99, 'c': 3}

Right side wins on shared keys

>>> d1 = {'a': 1}
>>> d2 = {'b': 2}
>>> d3 = d1 | d2
>>> d1, d2, d3
({'a': 1}, {'b': 2}, {'a': 1, 'b': 2})

Non-mutating — d1 and d2 are unchanged

>>> {'a': 1} | [('b', 2)]
Traceback (most recent call last):
  ...
TypeError: unsupported operand type(s) for |: 'dict' and 'list'

Both operands must be dicts — unlike update()

>>> defaults = {'timeout': 30, 'retries': 3}
>>> user = {'retries': 5}
>>> defaults | user
{'timeout': 30, 'retries': 5}

Idiomatic 'user overrides defaults' pattern

Gotcha

Requires Python 3.9+ (PEP 584) — use {**d1, **d2} for older versions. Both operands must be dicts; update() is more permissive with iterables and kwargs.

Related methods

← All Python dict methods · String methods · Built-in functions