添加计数器时如何保留原始字典

3 python counter dictionary python-2.7

据我了解,我知道何时调用Counter秘密词典。该字典包含的键值为零将会消失。

from collections import Counter

a = {"a": 1, "b": 5, "d": 0}
b = {"b": 1, "c": 2}

print Counter(a) + Counter(b)
Run Code Online (Sandbox Code Playgroud)

如果我想保留钥匙,该怎么办?

这是我的预期结果:

Counter({'b': 6, 'c': 2, 'a': 1, 'd': 0})
Run Code Online (Sandbox Code Playgroud)

Ana*_*mar 5

您还可以使用update()Counter 的方法代替+运算符,例如 -

>>> a = {"a": 1, "b": 5, "d": 0}
>>> b = {"b": 1, "c": 2}
>>> x = Counter(a)
>>> x.update(Counter(b))
>>> x
Counter({'b': 6, 'c': 2, 'a': 1, 'd': 0})
Run Code Online (Sandbox Code Playgroud)

update()函数添加计数而不是替换它们,并且它也不会删除零值 1。我们也可以先做Counter(b),然后更新Counter(a),示例 -

>>> y = Counter(b)
>>> y.update(Counter(a))
>>> y
Counter({'b': 6, 'c': 2, 'a': 1, 'd': 0})
Run Code Online (Sandbox Code Playgroud)