从python字典中删除重复键但总结值

use*_*568 2 python duplicates

我在python中有一本字典

d = {tags[0]: value, tags[1]: value, tags[2]: value, tags[3]: value, tags[4]: value}
Run Code Online (Sandbox Code Playgroud)

想象这个dict大10倍,它有50个键和50个值.可以在此标签中找到重复项,但即使这样,值也是必不可少的.我怎样才能简单地修剪它以重新获得新的字典而不需要复制键,而是使用值的总和?

d = {'cat': 5, 'dog': 9, 'cat': 4, 'parrot': 6, 'cat': 6}

结果

d = {'cat': 15, 'dog': 9, 'parrot': 6}

Alf*_*lfe 6

我想改进Paul Seeb的答案:

tps = [('cat',5),('dog',9),('cat',4),('parrot',6),('cat',6)]
result = {}
for k, v in tps:
  result[k] = result.get(k, 0) + v
Run Code Online (Sandbox Code Playgroud)


Aka*_*all 5

tps = [('cat',5),('dog',9),('cat',4),('parrot',6),('cat',6)]

from collections import defaultdict

dicto = defaultdict(int)

for k,v in tps:
    dicto[k] += v
Run Code Online (Sandbox Code Playgroud)

结果:

>>> dicto
defaultdict(<type 'int'>, {'dog': 9, 'parrot': 6, 'cat': 15})
Run Code Online (Sandbox Code Playgroud)