【发布时间】:2020-02-16 20:37:06
【问题描述】:
例如,我有两本字典。
>>> dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
>>> dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}
我使用collections.Counter 进行计数。
>>> dict_c = Counter()
>>> dict_c.update(Counter(dict_a))
>>> dict_c.update(Counter(dict_b))
>>> print(dict_c)
{'toal': 50, 'remaining': 39, 'group': 'group_agroup_a'}
有没有办法只添加整数类型的值?即,当添加时,它仅将整数类型值相加。
>>> print(dict_c)
>>> {'toal': 50, 'remaining': 39, 'group': 'group_a'}
【问题讨论】:
-
预期输出是什么?
-
运行你的代码,我得到
TypeError: unsupported operand type(s) for +: 'dict' and 'dict' -
我已经更新了代码。 @zamir 我在最后添加了预期的输出。
-
你不能像那样添加字典,所以你现在得到的例子是不正确的。
-
@martineau 我正在使用集合中的计数器进行添加。为什么不能正确?能详细点吗?
标签: python dictionary collections counter