You can merge two dictionaries into a new one using several methods depending on your Python version.
When a key exists in both dictionaries, the second dictionary’s value overwrites the first.
Starting from Python 3.9, you can use the merge (|) and update (|=) operators:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = x | y
print(z)
{'a': 1, 'b': 3, 'c': 4}
| creates a new merged dictionary.
|= updates the existing one (similar to .update()).
For Python 3.5 and later:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
print(z)
{'a': 1, 'b': 3, 'c': 4}
Here, unpacking (**) expands both dictionaries into a new one, and values from y overwrite duplicates from x.
If you’re using an older version of Python:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = x.copy()
z.update(y)
print(z)
{'a': 1, 'b': 3, 'c': 4}
Work with our skilled Python developers to accelerate your project and boost its performance.
Hire Python Developers