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

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

    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)
    
    0 讨论(0)
提交回复
热议问题