Python Glossary Русский

Python 3.9+Dictionaries (dict)term

d1 | d2

operators

The dictionary merge operator (Python 3.9+). It builds a new dictionary out of d1 and d2. On a key conflict the right operand wins.

Syntax

merged = d1 | d2

Both operands must be actual dicts: a | [('x', 1)] raises TypeError, while a |= [('x', 1)] and a.update([...]) accept such a list of pairs. The operator builds a brand-new dict by copying both sides in full, so merging many dicts in a loop turns quadratic — reach for update() or |= there. Before 3.9 the same effect came from {**a, **b}.

Examples

a = {'x': 1, 'y': 2}
b = {'y': 10, 'z': 3}
result = a | b
print(result)  # {'x': 1, 'y': 10, 'z': 3}
# аналог без оператора (до 3.9):
result = {**a, **b}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy