Removing duplicate keys from python dictionary but summing the values

前端 未结 8 1996
陌清茗
陌清茗 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 06:01
    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
    

    Result:

    >>> dicto
    defaultdict(<type 'int'>, {'dog': 9, 'parrot': 6, 'cat': 15})
    
    0 讨论(0)
  • 2021-01-15 06:02

    If I understand correctly your question that you want to get rid of duplicate key data, use update function of dictionary while creating the dictionary. it will overwrite the data if the key is duplicate.

    tps = [('cat',5),('dog',9),('cat',4),('parrot',6),('cat',6)]
    result = {}
    for k, v in tps:
        result.update({k:v})
    for k in result:
        print "%s: %s" % (k, result[k]) 
    

    Output will look like: dog: 9 parrot: 6 cat: 6

    0 讨论(0)
提交回复
热议问题