尝试添加 2 个反字典

Trying to add 2 Counter dictionaries

正在尝试在 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'>

请告诉我哪里错了。

你能再检查一下你的代码吗?这是我的代码:

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})