试图添加2个Counter词典

时间:2017-02-06 23:21:05

标签: python python-3.x dictionary counter

尝试在Python 3中添加2个Python词典。

例如:

dict1 = {'a': 10,'b':20}
dict2 =  {'a': 30,'b':30}

预期结果:

dict_sum = {'a': 40,'b':50}

代码:

A = Counter (dict1)
B = Counter(dict2)
dict_sum = A + B

结果:

Counter() #empty counter object

仍然得到一个空的反对象。

我在AB中检查了键和值的类型,结果如下:

<class 'dict_values'>
<class 'dict_keys'>

请告诉我哪里出错了。

1 个答案:

答案 0 :(得分:-1)

你能再次查看你的代码吗?这是我的代码:

from collections import Counter


dict1 = {'a': 10,'b': 20}
dict2 = {'a': 30,'b': 30}

new_counter = Counter(dict1) + Counter(dict2)
print(new_counter)

# Counter({'b': 50, 'a': 40})

致@vikky:首先检查您的环境。这段代码效果很好。如果它不起作用,您可能需要先检查您的环境。

$ python
Python 2.7.12 (default, Jun 29 2016, 14:05:02) 
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import Counter
>>> dict1 = {'a': 10, 'b': 20}
>>> dict2 = {'a': 30, 'b': 30}
>>> Counter(dict1) + Counter(dict2)
Counter({'b': 50, 'a': 40})

它也适用于Python 3.

$ python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import Counter
>>> dict1 = {'a': 10, 'b': 20}
>>> dict2 = {'a': 30, 'b': 30}
>>> Counter(dict1) + Counter(dict2)
Counter({'b': 50, 'a': 40})