【发布时间】:2021-08-09 15:46:56
【问题描述】:
我想用另一个扩展一个给定的字典,但如果一个键已经存在,我必须累积值。
例子:
让我们考虑一个称为累积更新的给定函数和两个字典 a 和 b:
a = { "a" : 1, "b" : 2, "c" : 1 }
b = { "c" : 3, "d" : 4 }
a.cumulative_update(b)
想要的结果应该是:
{'a': 1, 'b': 2, 'c': 4, 'd': 4}
但是,当我使用默认的附加功能时:
a.update(b)
我明白了:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
我还找到了在 How to sum values of the same key in a dictionary? 中附加值的解决方案,但它基于在我的情况下不可能的键。
【问题讨论】:
-
这是
collections.Counter真正闪耀的地方:example。 -
geeksforgeeks.org/… 这可能是一本好书。请检查解决方案
-
是的,很好,我们可以使用计数器
标签: python python-3.x function dictionary