Removing duplicate keys from python dictionary but

2019-02-26 12:57发布

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}

8条回答
ゆ 、 Hurt°
2楼-- · 2019-02-26 13:29

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
查看更多
叛逆
3楼-- · 2019-02-26 13:29

Instead of just doing dict of those things (can't have multiples of same key in a dict) I assume you can have them in a list of tuple pairs. Then it is just as easy as

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

>>> result
{'dog': 9, 'parrot': 6, 'cat': 15}

changed mine to more explicit try-except handling. Alfe's is very concise though

查看更多
登录 后发表回答