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

前端 未结 7 773
后悔当初
后悔当初 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:02

    In case when you have dictionaries with the same size and keys you can use the following code:

    dict((k,v if k in d2 and d2[k] in [None, ''] else d2[k]) for k,v in d1.iteritems())
    

提交回复
热议问题