python多个条件组合覆盖,Python:字典通过更新合并,但如果值存在则不覆盖

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.

解决方案

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 response to the edit] 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值