merge
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.
d1 |= other Parameters
| Parameter | Purpose |
|---|---|
| left operand | Dict mutated in place |
| right operand | Mapping OR iterable of (key, value) pairs |
Examples
>>> d = {'a': 1, 'b': 2}
>>> d |= {'b': 99, 'c': 3}
>>> d
{'a': 1, 'b': 99, 'c': 3} Mutates d in place, right side wins
>>> d = {'a': 1}
>>> d |= [('b', 2), ('c', 3)]
>>> d
{'a': 1, 'b': 2, 'c': 3} Accepts an iterable of pairs (unlike plain |)
>>> d = {'a': 1}
>>> ref = d
>>> d |= {'b': 2}
>>> ref
{'a': 1, 'b': 2} In-place — aliases observe the change
>>> d = {'a': 1}
>>> d = d | {'b': 2}
>>> # equivalent RESULT to d |= ..., but rebinds instead of mutating Contrast with |, which creates a new dict
Gotcha
Requires Python 3.9+. |= mutates in place like update() — a rebinding 'd = d | other' produces a new dict and does NOT affect other references.
Related methods
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.
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[key] = value
Assigns value to key using bracket subscription syntax, invoking __setitem__ under the hood. Creates the entry if key is absent, or overwrites the existing value; preserves the original insertion order when the key already exists.
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.
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.
← All Python dict methods · String methods · Built-in functions