【问题标题】:How to add the values in dictionary with same keys [duplicate]如何使用相同的键在字典中添加值[重复]
【发布时间】:2020-01-15 05:36:38
【问题描述】:

如何添加具有相同键的值。有没有像sum(int(v)))这样的在线黑客可以做的事情?

m = {'Rash': 1, 'Manjeet': 1, 'Akash': 3}, {'Rash': 3, 'Manjeet': 4, 'Akash': 4}
l = []
for i in m:
    #print (i)
    for j in i.items():
        l.append(j)
from collections import defaultdict
f = defaultdict(list)
for k, v in l:
    f[k].append(int(v)) #hack
for i,j in f.items():
    print (i,sum(j)) 

我的出局

Rash 4
Manjeet 5
Akash 7

我的预期

{'Rash': 4, 'Manjeet': 5, 'Akash': 7}

【问题讨论】:

  • 您发布的内容有什么问题

标签: python dictionary


【解决方案1】:

您可以使用collections.Counter 来获得更简单的方法:

from collections import Counter
c = Counter()
for d in m:
    c += d

print(c)
# Counter({'Akash': 7, 'Manjeet': 5, 'Rash': 4})

或者使用defaultdict:

out = defaultdict(int)
for d in m:
    for k,v in d.items():
        out[k] += v

print(out)
# defaultdict(<class 'int'>, {'Rash': 4, 'Manjeet': 5, 'Akash': 7})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    相关资源
    最近更新 更多