是否有任何pythonic方式组合两个dicts(添加两个键出现的值)? [英] Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
本文介绍了是否有任何pythonic方式组合两个dicts(添加两个键出现的值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Dict A:{'a':1,'b':2, 'c':3}
Dict B:{'b':3,'c':4,'d':5}
我需要一个组合两个dict的pythonic方式,结果是:
{'a':1,'b':5,'c':7,'d':5}
也就是说:如果一个键出现在两个dict中,添加它们的值,如果它只出现在一个dict中,保持其值。
解决方案
使用 集合。计数器
:
>>>从集合导入计数器
>>>> A = Counter({'a':1,'b':2,'c':3})
>>> B = Counter({'b':3,'c':4,'d':5})
>>> A + B
计数器({'c':7,'b':5,'d':5,'a':1})
计数器基本上是 dict
的子类,所以你仍然可以和他们通常做的一切该类型,例如迭代其键和值。
For example I have two dicts:
Dict A: {'a':1, 'b':2, 'c':3}
Dict B: {'b':3, 'c':4, 'd':5}
I need a pythonic way of 'combining' two dicts such that the result is :
{'a':1, 'b':5, 'c':7, 'd':5}
That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its value.
解决方案
Use collections.Counter
:
>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})
Counters are basically a subclass of dict
, so you can still do everything else with them you'd normally do with that type, such as iterate over their keys and values.
这篇关于是否有任何pythonic方式组合两个dicts(添加两个键出现的值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文