Removing duplicate keys from python dictionary but summing the values

前端 未结 8 2069
陌清茗
陌清茗 2021-01-15 05:30

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 i

8条回答
  •  日久生厌
    2021-01-15 05:55

    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
    

提交回复
热议问题