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

前端 未结 7 787
后悔当初
后悔当初 2020-12-15 02:48

If I have 2 dicts as follows:

d1 = {(\'unit1\',\'test1\'):2,(\'unit1\',\'test2\'):4}
d2 = {(\'unit1\',\'test1\'):2,(\'unit1\',\'test2\'):\'\'}
7条回答
  •  清歌不尽
    2020-12-15 03:04

    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
    

提交回复
热议问题