【问题标题】:How to add values from different dict based on their key [closed]如何根据键添加来自不同字典的值[关闭]
【发布时间】:2016-03-15 15:11:10
【问题描述】:

例如我有两个字典:

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

虽然 update() 函数可以刷新旧值,比如

a.update(b)

会回来

{'a': 2, 'b': 0, 'c': 5, 'd': 4}

但我想要他们的总和,换句话说,我想要拥有

{'a': 3, 'b': 0, 'c': 5, 'd': 4}

所以'a'的值是两个dict的总和

我该怎么做?

【问题讨论】:

  • 我该怎么做? 通过编写代码任何人都可以为我编写代码吗? 不,SO 不适合 gimmetehcodez。做一些研究和复出,我们将非常乐意为您提供帮助
  • 看看collections.defaultdict

标签: python dictionary


【解决方案1】:

以下代码将以您想要的方式更新a

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

for k, v in b.iteritems():
    a[k] = a.get(k, 0) + v

print a # {'a': 3, 'c': 5, 'b': 0, 'd': 4}

【讨论】:

    【解决方案2】:

    collections.Counter 可能会给你你想要的。 collections.Counter.update() 的文档说:

    类似于 dict.update() 但添加计数而不是替换它们。

    from collections import Counter
    
    a = Counter({'a':1, 'b':0, 'c':5})
    b = {'d':4, 'a':2}
    
    a.update(b)
    
    print a
    

    结果:

    Counter({'c': 5, 'd': 4, 'a': 3, 'b': 0})
    

    【讨论】:

    • 谢谢!这就是我想要的,抱歉我的描述含糊,因为我是新手。
    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2017-09-06
    • 2018-03-22
    • 2014-01-02
    相关资源
    最近更新 更多