Python 3.9+Dictionaries (dict)term
| dict merge operator
operators
The | operator (Python 3.9+) merges two dictionaries into a new one. For a key present in both, the value comes from the right one. |= updates the dictionary in place.
Syntax
d1 | d2 d1 |= d2
The merge is shallow: nested lists and dicts in the result are the very same objects, so a change made through one dict shows up in the other. Key order follows the left operand — a shared key keeps its original position but takes the new value, while keys unique to the right operand are appended at the end.
Examples
a = {"x": 1, "y": 2}; b = {"y": 99, "z": 3}
print(a | b) # → {'x': 1, 'y': 99, 'z': 3}
print(b | a) # → {'y': 2, 'z': 3, 'x': 1}
a |= b; print(a) # → {'x': 1, 'y': 99, 'z': 3}
print({} | {"k": 1}) # → {'k': 1}
c = {"p": 5}; c |= {"q": 6}; print(c) # → {'p': 5, 'q': 6}
See also
Open in the full glossarydocs.python.orgReport an inaccuracy