【发布时间】:2011-09-15 07:33:51
【问题描述】:
如果我有 2 个字典如下:
d1 = {'a': 2, 'b': 4}
d2 = {'a': 2, 'b': ''}
为了“合并”它们:
dict(d1.items() + d2.items())
结果
{'a': 2, 'b': ''}
但是,如果我想比较两个字典的每个值,并且仅在 d1 中的值为空/None/'' 时将d2 更新为d1,我该怎么办?
当存在相同的键时,我只想保留数值(来自d1 或d2)而不是空值。如果两个值都为空,则保持空值没有问题。如果两者都有值,那么d1-value 应该保留。
即
d1 = {'a': 2, 'b': 8, 'c': ''}
d2 = {'a': 2, 'b': '', 'c': ''}
应该会导致
{'a': 2, 'b': 8, 'c': ''}
其中 8 未被'' 覆盖。
【问题讨论】:
-
你试过
in了吗? -
另见(基于 php)stackoverflow.com/questions/793464/…
-
另见(基于 ruby)stackoverflow.com/questions/1980794/…
-
另见:(itemgetter)stackoverflow.com/a/12118794/42223
标签: python dictionary merge compare