Python:字典通过更新合并,但如果值存在则不覆盖 [英] Python: Dictionary merge by updating but not overwriting if value exists

查看:2267
本文介绍了Python:字典通过更新合并,但如果值存在则不覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个dict如下:

  d1 = {('unit1','test1'):2, ('unit1','test2'):4} 
d2 = {('unit1','test1'):2,('unit1','test2'):'' code>

为了合并他们:

 code> z = dict(d1.items()+ d2.items())
z = {('unit1','test1'):2,('unit1','test2'):' '}

工作正常。
另外要做什么,如果我想比较两个字典的每个值,只有d1中的值为空,才将d2更新为d1 / $ / $ $ $ $ $ $ $ $问题:将d2更新为d1时,当存在相同的键时,我只想保留数值(从d1或d2),而不是空值。如果两个值都为空,那么没有问题维护空值。如果两者都有值,则d1值应该保留。 :)(很多if-else ..我会同时尝试自己)



ie

  d1 = {('unit1','test1'):2,('unit1','test2'):8,('unit1','test3'):''} 
d2 = {('unit1','test1'):2,('unit1','test2'):'',('unit1','test3'):''}

#compare&更新代码

z = {('unit1','test1'):2,('unit1','test2'):8,('unit1','test2'):'' 8没有被空的覆盖。

请帮忙建议。



谢谢

解决方案

只需切换顺序:

 code> z = dict(d2.items()+ d1.items())

顺便说一下,您可能还会对 更新 方法。






[响应编辑]如果你想要特殊情况下的空字符串,你可以执行以下操作:

  def mergeDictsOverwriteEmpty(d1,d2):
res = d2.copy()
for k,v in d2.items():
如果k不在d1或d1 [k] ==':
res [k ] = v
return res


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

这篇关于Python:字典通过更新合并,但如果值存在则不覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆