从python字典中删除重复的键,但对值进行求和 [英] Removing duplicate keys from python dictionary but summing the values

查看:194
本文介绍了从python字典中删除重复的键,但对值进行求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个字典

  d = {tags [0]:value,tags [1]标签[2]:value,tags [3]:value,tags [4]:value} 

想象这个dict是1​​0倍,它有50个键和50个值。这个标签中可以找到重复的,但即使这样,值也是至关重要的。我如何简单地修剪它,以回收新的字典,而不需要重复键,而是使用值的总和?



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



p>

d = {'cat':15,'dog':9,'parrot':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
pre>

I have a dictionary in python

d = {tags[0]: value, tags[1]: value, tags[2]: value, tags[3]: value, tags[4]: value}

imagine that this dict is 10 times bigger, it has 50 keys and 50 values. Duplicates can be found in this tags but even then values are essential. How can I simply trimm it to recive new dict without duplicates of keys but with summ of values instead?

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

result

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

解决方案

I'd like to improve Paul Seeb's answer:

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

这篇关于从python字典中删除重复的键,但对值进行求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆