Skip to content
Tutorials Center
My learning

Topics

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 |.

Python
defaults = {"theme": "light", "size": 12}
user = {"size": 16}
defaults | user   # {'theme': 'light', 'size': 16}

Try it

Python Merged copy with |

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.

Python In-place merge with |=

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

Python
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. After x = a | b, a is unchanged. After a |= 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 from b; an overwritten key keeps its original position.
  • |= is update(). It accepts anything dict.update() accepts, including pairs; | is stricter and returns NotImplemented for non-mappings, which becomes a TypeError.
  • Shallow merge. Nested dictionaries are replaced entirely, not merged recursively.
  • Python version. Needs 3.9 or newer. On earlier versions use {**a, **b} or update().
  • Subclasses: defaultdict and OrderedDict support the operators too; the result keeps the type of the left operand.