从两个字典中添加值 [英] Add values from two dictionaries

查看:75
本文介绍了从两个字典中添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dict1 = {a: 5, b: 7}
dict2 = {a: 3, c: 1}

result {a:8, b:7, c:1}

如何获得结果?

推荐答案

这是一个单行代码,可以做到这一点:

this is a one-liner that would do just that:

dict1 = {'a': 5, 'b': 7}
dict2 = {'a': 3, 'c': 1}

result = {key: dict1.get(key, 0) + dict2.get(key, 0)
          for key in set(dict1) | set(dict2)}
# {'c': 1, 'b': 7, 'a': 8}

请注意,set(dict1) | set(dict2)是两个词典的键集.如果键存在,则dict1.get(key, 0)返回dict1[key],否则返回0.

note that set(dict1) | set(dict2) is the set of the keys of both your dictionaries. and dict1.get(key, 0) returns dict1[key] if the key exists, 0 otherwise.

这篇关于从两个字典中添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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