How to merge two dictionaries in a single expression with Python?

Sometimes, we want to merge two dictionaries in a single expression with Python.

In this article, we’ll look at how to merge two dictionaries in a single expression with Python.

How to merge two dictionaries in a single expression with Python?

To merge two dictionaries in a single expression with Python, we can use the ** or | operators.

For instance, we write:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
print(z)

Then z is {'a': 1, 'b': 3, 'c': 4}.

** is available since Python 3.5.

We can also use the | operator with Python 3.9 or later.

To use it, we write:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = x | y

And we get the same value for z.

Conclusion

To merge two dictionaries in a single expression with Python, we can use the ** or | operators.