【问题标题】:Extend a dict with anoter dict with cumulative values result用另一个具有累积值结果的 dict 扩展一个 dict
【发布时间】: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? 中附加值的解决方案,但它基于在我的情况下不可能的键。

【问题讨论】:

标签: python python-3.x function dictionary


【解决方案1】:
a = { "a" : 1, "b" : 2, "c" : 1 }
b = { "c" : 3, "d" : 4 }


result = {key: a.get(key, 0) + b.get(key, 0) for key in set(a) | set(b)}

输出:

{'a': 1, 'b': 2, 'd': 4, 'c': 4}

【讨论】:

    【解决方案2】:

    你可以使用Counter:

    from collections import Counter
    
    a = { "a" : 1, "b" : 2, "c" : 1 }
    b = { "c" : 3, "d" : 4 }
    
    result = Counter(a) + Counter(b)
    

    输出:

    Counter({'c': 4, 'd': 4, 'b': 2, 'a': 1})
    

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多