I’m looking for a one-liner to Python merge dictionaries x and y into a new dictionary z, where overlapping keys should take the value from y.
Example:
x = {‘a’: 1, ‘b’: 2}
y = {‘b’: 3, ‘c’: 4}
z = merge(x, y)
Expected result:
{‘a’: 1, ‘b’: 3, ‘c’: 4}
What’s the best single-expression way to achieve this merge behavior in modern Python?
I’ve been working with Python for over a decade now, and if you’re using Python 3.9 or later, the cleanest and most intuitive way I’ve seen to python merge dictionaries is with the |
operator. It’s tailor-made for this:
z = x | y
This creates a new dictionary z
where any overlapping keys will prefer values from y
. I like how this doesn’t mutate the original dicts, keeps things tidy, especially in production code.
Totally agree, @jacqueline-bosco. For folks who might still be on Python 3.5+ or working across environments, I’ve found unpacking with **
to be super reliable when I need to python merge dictionaries on the fly:
z = {**x, **y}
This also creates a new dict, and like with the merge operator, values from y
win if keys clash. I use this a lot in CLI tools and config loaders — keeps the code clean without worrying about version compatibility.
Yep, and building on both your points, if you’re dealing with dynamically passed dicts or even custom merging logic, this one’s helped me a lot:
z = dict(x.items() | y.items())
This lets you python merge dictionaries in a way that feels more explicit, especially when visualizing or manipulating key-value pairs during debugging. It gives me more flexibility when chaining transformations or applying filters before merging