"添加" Python中的字典? [英] "Adding" Dictionaries in Python?

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

问题描述


可能重复:

python dict.add_by_value(dict_2)?


我的输入是两个具有字符串键和整数值的字典。我想添加两个字典,以便结果具有输入字典的所有键,并且这些值是输入字典值的总和。



为了清楚起见,如果一个键仅显示在一个输入中,则该键/值将显示在结果中,而如果键出现在两个字典中,则总和值得出现在结果中。



例如,说我的输入是:

 code> a = dict()
a ['cat'] = 1
a ['fish'] = 10
a ['aardvark'] = 1000

b = dict()
b ['cat'] = 2
b ['dog'] = 200
b ['aardvark'] = 2000
/ pre>

我希望结果是:

  'cat':3,'fish':10,'dog':200,'aardvark':3000} 



知道Python必须有一个一线程来完成这个工作(它不一定是一行...)。任何想法?

解决方案

如何做:

 set(a)| set(b)]中的n的 dict([(n,a.get(n,0)+ b.get(n,0)))

或不创建中间列表(生成器就够了):



<$ p $ set



$ b






Post Scriptum:



正如评论员正确地解决的那样,有一种方法可以使用新的(从Py2.7)collections.Counter类来实现。我记得很多,当我写了答案时,这个版本不可用:

 从集合导入计数器
dict柜台(a)+柜台(b))


Possible Duplicate:
python dict.add_by_value(dict_2) ?

My input is two dictionaries that have string keys and integer values. I want to add the two dictionaries so that the result has all the keys of the input dictionaries, and the values are the sum of the input dictionaries' values.

For clarity, if a key appears in only one of the inputs, that key/value will appear in the result, whereas if the key appears in both dictionaries, the sum of values will appear in the result.

For example, say my input is:

a = dict()
a['cat'] = 1
a['fish'] = 10
a['aardvark'] = 1000

b = dict()
b['cat'] = 2
b['dog'] = 200
b['aardvark'] = 2000

I would like the result to be:

{'cat': 3, 'fish': 10, 'dog': 200, 'aardvark': 3000}

Knowing Python there must be a one-liner to get this done (it doesn't really have to be one line...). Any thoughts?

解决方案

How about that:

dict( [ (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) ] )

Or without creating an intermediate list (generator is enough):

dict( (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) )


Post Scriptum:

As a commentator addressed correctly, there is a way to implement that easier with the new (from Py2.7) collections.Counter class. As much I remember, this version was not available when I wrote the answer:

from collections import Counter
dict(Counter(a)+Counter(b))

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

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