I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict 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 dict 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.)
For dictionaries x and y, z becomes a shallowly merged dictionary with values from y replacing those from x.
z = {**x, **y}
def merge_two_dicts(x, y):
# start with x's keys and values
z = x.copy()
# modifies z with y's keys and values & returns None
z.update(y)
return z
z = merge_two_dicts(x, y)
网友评论