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
dict1 |= dict2
In-place merge operator (Python 3.9+) that updates d1 with entries from other, with other's values winning on shared keys. Unlike |, the right operand can be any iterable of pairs or a mapping — matching update()'s flexibility.
dict.update
Updates the dictionary in place with key/value pairs from other, overwriting existing keys. Accepts another mapping, an iterable of key/value pairs, and/or keyword arguments; returns None.
dict.copy
Returns a shallow copy of the dictionary — a new dict object with the same key-value pairs. Values themselves are not copied, so nested mutable objects are still shared between the original and the copy.
dict.fromkeys
Class method that builds a new dict whose keys come from iterable and whose values are all set to value (default None). The same value object is shared across every key — beware mutable defaults.
← All Python dict methods · String methods · Built-in functions