【发布时间】:2020-11-14 00:50:02
【问题描述】:
我尝试将其他字典中存在的键的值与此代码相加:
import functools
import operator
import collections
my_dict = [{'a':0, 'b':1, 'c':5}, {'b':3, 'c':2}, {'b':1, 'c':1}]
sum_key_value = functools.reduce(operator.add, map(collections.Counter, my_dict))
print(sum_key_value)
# Output
# Counter({'c': 8, 'b': 5})
我的问题是,如果我希望输出保留所有字典键,即使在我的情况下该键没有出现在像 a 这样的所有字典中,不使用循环的最佳方法是什么?
【问题讨论】:
-
Python 文档中指出,在
Counter对象上进行添加操作(这是您的代码中发生的情况)将删除带有 0 的值:每个操作都可以接受输入签名计数,但输出将排除计数为零或更少的结果 (docs.python.org/3/library/collections.html#collections.Counter)
标签: python dictionary