Python Glossary Русский

all Python 3Dictionaries (dict)term

Merging dictionaries

operators

update() modifies the dictionary in place. ** unpacking builds a new one. | (Python 3.9+) is the merge operator.

Syntax

d1.update(d2)  |  {**d1, **d2}  |  d1 | d2

update() returns None, so writing d = d1.update(d2) silently leaves you with None — the classic mistake here. Picking a method comes down to one question: do you still need the original dict untouched. All three variants copy values by reference, so nested lists and dicts stay shared with the originals.

Examples

# Python 3.9+
d1 = {'a': 1, 'b': 2}
d2 = {'b': 20, 'c': 3}
d1.update(d2)
print(d1)
# → {'a': 1, 'b': 20, 'c': 3}
d3 = {'a': 1, 'b': 2}
merged = {**d3, **d2}
print(merged)
# → {'a': 1, 'b': 20, 'c': 3}
d4 = d3 | d2
print(d4)
# → {'a': 1, 'b': 20, 'c': 3} (Python 3.9+)
extra = {'x': 9}
combined = {**d3, **d2, **extra}
print(combined)
# → {'a': 1, 'b': 20, 'c': 3, 'x': 9}
print(d3)
# → {'a': 1, 'b': 2} (** не изменяет оригинал)
# Python 3.9+
d5 = {'a': 1}
d5 |= {'b': 2, 'a': 99}
print(d5)
# → {'a': 99, 'b': 2}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy