Python: Dictionary merge by updating but not overwriting if value exists

siva picture siva · Jun 15, 2011 · Viewed 60.9k times · Source

If I have 2 dicts as follows:

d1 = {('unit1','test1'):2,('unit1','test2'):4}
d2 = {('unit1','test1'):2,('unit1','test2'):''}

In order to 'merge' them:

z = dict(d1.items() + d2.items())
z = {('unit1','test1'):2,('unit1','test2'):''}

Works fine. Additionally what to be done, if i would like to compare each value of two dictionaries and only update d2 into d1 if values in d1 are empty/None/''?

[EDIT] Question: When updating d2 into d1, when the same key exists, I would like to only maintain the numerical value (either from d1 or d2) instead of empty value. If both values are empty, then no problems maintaining empty value. If both have values, then d1-value should stay. :) (lotsa if-else .. i'd try myself in the meantime)

i.e.

d1 = {('unit1','test1'):2,('unit1','test2'):8,('unit1','test3'):''}
d2 = {('unit1','test1'):2,('unit1','test2'):'',('unit1','test3'):''}

#compare & update codes

z = {('unit1','test1'):2,('unit1','test2'):8, ('unit1','test2'):''} # 8 not overwritten by empty.

please help to suggest.

Thanks.

Answer

phihag picture phihag · Jun 15, 2011

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