字典通过更新合并,但如果值存在则不覆盖

编程入门 行业动态 更新时间:2024-10-27 13:33:08
本文介绍了字典通过更新合并,但如果值存在则不覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

字典通过更新合并,但如果值存在则不覆盖

本文发布于:2023-10-20 09:14:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1510551.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!