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

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

问题描述

如果我有 2 个字典如下:

If I have 2 dicts as follows:

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

为了合并"它们:

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

工作正常.另外要做什么,如果我想比较两个字典的每个值,并且仅当 d1 中的值为空/无/''时才将 d2 更新为 d1?

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/''?

问题:当将d2更新为d1时,当存在相同的键时,我只想保持数值(来自d1或d2)而不是空值.如果两个值都为空,则保持空值没有问题.如果两者都有值,则 d1-value 应该保留.:) (lotsa if-else ..在此期间我会尝试自己)

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)

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.

请帮忙提出建议.

谢谢.

推荐答案

换个顺序就行了:

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

顺便说一句,您可能还对可能更快的感兴趣更新方法.

By the way, you may also be interested in the potentially faster update method.

在 Python 3 中,您必须先将视图对象转换为列表:

In Python 3, you have to cast the view objects to lists first:

z = dict(list(d2.items()) + list(d1.items())) 

如果要对空字符串进行特殊处理,可以执行以下操作:

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天全站免登陆