How do I merge two dictionaries in a single expression in Python (taking union of dictionaries)?

Submitted 4 years, 6 months ago
Ticket #206
Views 301
Language/Framework Python
Priority Low
Status Closed

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place.

>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 10, 'c': 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{'a': 1, 'b': 10, 'c': 11}

How can I get that final merged dictionary in z, not x?

(To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I'm looking for as well.)

Submitted on Oct 04, 20
add a comment

2 Answers

z = x.copy()

z.update(y)

It's how dict works. Keys should be unique. You can keep values in list, like described here

Submitted 4 years, 6 months ago


Verified

For dictionaries x and yz becomes a shallowly merged dictionary with values from y replacing those from x.

In Python 3.5 or greater:

	z = {**x, **y}
	In Python 2, (or 3.4 or lower) write a function:
	def merge_two_dicts(x, y):
	    z = x.copy()   # start with x's keys and values
	    z.update(y)    # modifies z with y's keys and values & returns None
	    return z
and now:
z = merge_two_dicts(x, y)

Submitted 4 years, 6 months ago


Latest Blogs