Removing duplicate keys from python dictionary but summing the values

前端 未结 8 2003
陌清茗
陌清茗 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:58

    This the perfect situation for using Counter data structure. Lets take a look on what it does on few familiar data structures. Lets start with good old list.

    >>> from collections import Counter
    >>> list_a = ["A", "A", "B", "C", "C", "A", "D"]
    >>> list_b = ["B", "A", "B", "C", "C", "C", "D"]
    >>> c1 = Counter(list_a)
    >>> c2 = Counter(list_b)
    >>> c1
    Counter({'A': 3, 'C': 2, 'B': 1, 'D': 1})
    >>> c2
    Counter({'C': 3, 'B': 2, 'A': 1, 'D': 1})
    >>> c1 - c2
    Counter({'A': 2})
    >>> c1 + c2
    Counter({'C': 5, 'A': 4, 'B': 3, 'D': 2})
    >>> c_diff = c1 - c2
    >>> c_diff.update([77, 77, -99, 0, 0, 0])
    >>> c_diff
    Counter({0: 3, 'A': 2, 77: 2, -99: 1})
    

    As you can see this behaves as a set that keeps the count of element occurrences as a value. Hm, but what about using a dictionary instead of a list? The dictionary in itself is a set-like structure where for values we don't have to have numbers, so how will that get handled? Lets take a look.

    >>> dic1 = {"A":"a", "B":"b"}
    >>> cd = Counter(dic1)
    >>> cd
    Counter({'B': 'b', 'A': 'a'})
    >>> cd.update(B='bB123')
    >>> cd
    Counter({'B': 'bbB123', 'A': 'a'})
    
    
    >>> dic2 = {"A":[1,2], "B": ("a", 5)}
    >>> cd2 = Counter(dic2)
    >>> cd2
    Counter({'B': ('a', 5), 'A': [1, 2]})
    >>> cd2.update(A=[42], B=(2,2))
    >>> cd2
    Counter({'B': ('a', 5, 2, 2), 'A': [1, 2, 42, 42, 42, 42]})
    >>> cd2 = Counter(dic2)
    >>> cd2
    Counter({'B': ('a', 5), 'A': [1, 2]})
    >>> cd2.update(A=[42], B=("new elem",))
    >>> cd2
    Counter({'B': ('a', 5, 'new elem'), 'A': [1, 2, 42]})
    

    As you can see the value we are adding/changing has to be of the same type in update or it throws TypeError. As for your particular case just go with the flow

    >>> d = {'cat': 5, 'dog': 9, 'cat': 4, 'parrot': 6, 'cat': 6}
    >>> cd3 = Counter(d)
    >>> cd3
    Counter({'dog': 9, 'parrot': 6, 'cat': 6})
    cd3.update(parrot=123)
    cd3
    Counter({'parrot': 129, 'dog': 9, 'cat': 6})
    

提交回复
热议问题