Merging dictionaries in Python is a common task, and there are a few ways to do it:
- The unpacking operator
**
- The union operator
|
- The dict update operator
|=
The unpacking operator **
Since Python 3.5 (circa 2015), the simplest way to merge dictionaries has been with Python’s unpacking operator **
:
dict_one = {"first_name": "Nic"}
dict_two = {"last_name": "Cage"}
merged = {**first, **last}
# {"first_name": "Nic", "last_name": "Cage"}
It’s worth noting that if the objects being merged share a key, the last one given will win:
dict_one = {"first_name": "Nic"}
dict_two = {"first_name": "Luke", "last_name": "Cage"}
print({**dict_one, **dict_two})
# {"first_name": "Luke", "last_name": "Cage"}
# dict_two's "first_name" was the last one given
print({**dict_two, **dict_one})
# {"first_name": "Nic", "last_name": "Cage"}
The union operator |
With Python 3.9, released in late 2020, we have an even shorter option via the union operator |
:
dict_one = {"first_name": "Nic"}
dict_two = {"last_name": "Cage"}
merged = dict_one | dict_two
print(merged)
# {"first_name": "Nic", "last_name": "Cage"}
The dict update operator |=
Python 3.9 also introduced a dict update operator |=
. Instead of assigning the merged dictionary to a new variable, |=
modifies the left-hand dict in place, like so:
dict_one = {"first_name": "Nic"}
dict_two = {"last_name": "Cage"}
dict_one |= dict_two
print(dict_one)
# {"first_name": "Nic", "last_name": "Cage"}
The “last-seen” logic still applies with the |=
operator. So if both dicts have some matching keys, the last-seen key (the one on the right) will win, just like with **
.
Conclusion
I personally still use **
for a few reasons:
- Not all projects are on Python 3.9+ yet
- It allows for merging many objects if needed (though this is a bit rare)
- The
**kwargs
pattern is common in Python codebases, so using**
just feels natural