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'm not sure what you're trying to achieve, but the Counter class might be helpful for what you're trying to do: http://docs.python.org/dev/library/collections.html#collections.Counter
Result:
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.
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.
As you can see the value we are adding/changing has to be of the same type in
update
or it throwsTypeError
. As for your particular case just go with the flowPerhapse what you really want is a
tuple
of key-value pairs.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.
Output will look like: dog: 9 parrot: 6 cat: 6
This option serves but is done with a list, or best can provide insight