add values together and assign them to specific keys?

First, convert your list into a list of pairs (and this would work for separate keys and values lists too; pairs = list(zip(keys, values)) in that case):

>>> l = ['a',1,'b',2,'c',3,'a',2,'b',2]
>>> pairs = list(zip(l[::2], l[1::2]))
[('a', 1), ('b', 2), ('c', 3), ('a', 2), ('b', 2)]

Then use e.g. collections.Counter:

>>> from collections import Counter
>>> counter = Counter()
>>> for key, value in pairs:
...     counter[key] += value
...
>>> counter
Counter({'b': 4, 'a': 3, 'c': 3})

If you need just a dict, cast that:

>>> dict(counter)
{'a': 3, 'b': 4, 'c': 3}

Alternately, if you don’t want to use Counter, you can do this with a plain dict:

>>> d = {}
>>> for key, value in pairs:
...     d[key] = d.get(key, 0) + value

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top