Dictionary merge by updating but not overwriting if value exists
Solution 1:
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
Solution 2:
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.items() if v})
>>> d2
{'a': 1, 'c': 2, 'b': 2}
(Use iteritems()
instead of items()
in Python 2.)