Python Reference ยท Dictionaries and Sets
Python dict merge operators
Reference for the Python dict merge operators | and |= (3.9+): build a merged copy or update in place, how duplicates resolve, and how they compare to {**a, **b}.
Since Python 3.9, dictionaries support two merge operators. a | b returns a new dictionary containing the items of a followed by the items of b; where both have the same key, the value from b wins. a |= b updates a in place with the items of b.
They give a readable alternative to {**a, **b} and to calling copy() followed by update(). The operators work on dictionaries and other mappings of the same kind, and neither input is changed by |.
defaults = {"theme": "light", "size": 12} user = {"size": 16} defaults | user # {'theme': 'light', 'size': 16}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
new = a | b a |= b
| Name | Description |
|---|---|
a |
The left dictionary. With the in-place form it is modified. |
b |
The right operand. For the merged copy it must be a dictionary; for the in-place form it can be a mapping or an iterable of key-value pairs. |
Return value: a | b returns a new dictionary of the same type as a. a |= b modifies and returns a.
Raises: TypeError if b is not a suitable operand for |.
Usage notes
|copies,|=mutates. Afterx = a | b,ais unchanged. Aftera |= b, every other name bound to the same dictionary sees the change.- Right side wins for duplicate keys. Key order is
a's keys first, then new keys fromb; an overwritten key keeps its original position. |=isupdate(). It accepts anythingdict.update()accepts, including pairs;|is stricter and returnsNotImplementedfor non-mappings, which becomes aTypeError.- Shallow merge. Nested dictionaries are replaced entirely, not merged recursively.
- Python version. Needs 3.9 or newer. On earlier versions use
{**a, **b}orupdate(). - Subclasses:
defaultdictandOrderedDictsupport the operators too; the result keeps the type of the left operand.