Python: Dictionary merge by updating but not overwriting if value exists
Just switch the order:
z = dict(d2.items() + d1.items())
By the way, you may also be interested in the potentially faster update
method.
In Python 3, you have to cast the view objects to lists first:
z = dict(list(d2.items()) + list(d1.items()))
If you want to special-case empty strings, you can do the following:
def mergeDictsOverwriteEmpty(d1, d2): res = d2.copy() for k,v in d2.items(): if k not in d1 or d1[k] == '': res[k] = v return res
Python 2.7. Updates d2 with d1 key/value pairs, but only if d1 value is not None,'' (False):
>>> d1 = dict(a=1,b=None,c=2)>>> d2 = dict(a=None,b=2,c=1)>>> d2.update({k:v for k,v in d1.iteritems() if v})>>> d2{'a': 1, 'c': 2, 'b': 2}
To add to d2
keys/values from d1
which do not exist in d2
without overwriting any existing keys/values in d2
:
temp = d2.copy()d2.update(d1)d2.update(temp)