Python 3.5+Dictionaries (dict)term
Merging and ** unpacking of dictionaries
unpacking
** unpacks a dictionary into keyword arguments or builds a merged one. On duplicate keys the last one wins.
Syntax
func(**d) | {**d1, **d2} | d1 | d2 (Python 3.9+)
Both {**d1, **d2} and d1 | d2 copy shallowly: nested lists and dicts stay shared with the originals, so a change through one reference shows up in the other. The | operator (3.9+) demands real dicts on both sides, while {**a, **b} accepts any mapping; and in a call f(**d) every key must be a string or you get TypeError. For an in-place merge use d1 |= d2, the equivalent of update().
Examples
def greet(name, age):
return f'{name} is {age}'
info = {'name': 'Alice', 'age': 30}
print(greet(**info))
# → 'Alice is 30'
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
merged = {**d1, **d2}
print(merged)
# → {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d3 = {'a': 1}
d4 = {'a': 99, 'b': 2}
print({**d3, **d4})
# → {'a': 99, 'b': 2} (d4 перекрывает d3)
defaults = {'color': 'black', 'size': 'M'}
user_prefs = {'size': 'L'}
settings = {**defaults, **user_prefs}
print(settings)
# → {'color': 'black', 'size': 'L'}
print({**{'x': 1}, 'y': 2, **{'z': 3}})
# → {'x': 1, 'y': 2, 'z': 3}
See also
Open in the full glossarydocs.python.orgReport an inaccuracy