How to merge two Dictionaries in Python
This article shows different ways to merge two Dictionaries in Python.
This article shows different ways to merge two Dictionaries in Python.
#more
Python Dictionaries have an .update(other)
function that updates the dictionary with the key/value pairs from other, overwriting existing keys.
This, however, modifies the original dictionary in-place instead of returning a new one.
x = {'a': 1, 'b': 2}
y = {'b': 8, 'c': 9}
x.update(y)
# x: {'a': 1, 'b': 8, 'c': 9}
To create a new dictionary with the merged key/value pairs you can use different methods, depending on which Python version is used.
In Python 3.9 or greater:¶
z = x | y
# z: {'a': 1, 'b': 8, 'c': 9}
In Python 3.5 or greater:¶
z = {**x, **y}
# z: {'a': 1, 'b': 8, 'c': 9}
This is also known as dictionary unpacking. It was introduced in
PEP 448.
You can learn more about unpacking and different asterisk (*) use cases here.
Python 3.4 or lower:¶
z = x.copy()
z.update(y)
# z: {'a': 1, 'b': 8, 'c': 9}
Note that if you just use z = x
, only a shallow copy is created. This means that even after z has been updated, modifying x will also update z, and vice-versa.
So in order to create a true copy, x.copy()
is used here. You can learn more about shallow vs. deep copying here.
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*