As others have mentioned, a.update(b)
for some dicts a
and b
will achieve the result you've asked for in your question. However, I want to point out that many times I have seen the extend
method of mapping/set objects desire that in the syntax a.extend(b)
, a
's values should NOT be overwritten by b
's values. a.update(b)
overwrites a
's values, and so isn't a good choice for extend
.
Note that some languages call this method defaults
or inject
, as it can be thought of as a way of injecting b's values (which might be a set of default values) in to a dictionary without overwriting values that might already exist.
Of course, you could simple note that a.extend(b)
is nearly the same as b.update(a); a=b
. To remove the assignment, you could do it thus:
def extend(a,b):
"""Create a new dictionary with a's properties extended by b,
without overwriting.
>>> extend({'a':1,'b':2},{'b':3,'c':4})
{'a': 1, 'c': 4, 'b': 2}
"""
return dict(b,**a)
Thanks to Tom Leys for that smart idea using a side-effect-less dict
constructor for extend
.