Dictionary merge by updating but not overwriting if value exists(字典通过更新合并,但如果值存在则不覆盖)
问题描述
If I have 2 dicts as follows:
d1 = {'a': 2, 'b': 4}
d2 = {'a': 2, 'b': ''}
In order to 'merge' them:
dict(d1.items() + d2.items())
results in
{'a': 2, 'b': ''}
But what should I do if I would like to compare each value of the two dictionaries and only update d2
into d1
if values in d1
are empty/None
/''
?
When the same key exists, I would like to only maintain the numerical value (either from d1
or d2
) instead of the empty value. If both values are empty, then no problems maintaining the empty value. If both have values, then d1
-value should stay.
i.e.
d1 = {'a': 2, 'b': 8, 'c': ''}
d2 = {'a': 2, 'b': '', 'c': ''}
should result in
{'a': 2, 'b': 8, 'c': ''}
where 8 is not overwritten by ''
.
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 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 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01