Update Counter collection in python with string, not letter

Viewed 27602

How to update a Counter with a string, not the letters of the string? For example, after initializing this counter with two strings:

from collections import Counter
c = Counter(['black','blue'])

"add" to it another string such as 'red'. When I use the update() method it adds the letters 'r','e','d':

c.update('red')
c
>>Counter({'black': 1, 'blue': 1, 'd': 1, 'e': 1, 'r': 1})
6 Answers

I though it would be also good to give another example which you can both increase and decrease the number of counts

from collections import Counter

counter = Counter(["red", "yellow", "orange", "red", "orange"])
# to increase the count
counter.update({"yellow": 1})
# or
counter["yellow"] += 1

# to decrease
counter.update({"yellow": -1})
# or
counter["yellow"] -= 1

I just ran into the same problem recently. You can also put it in a tuple like this.

c.update(('red',))

The previous answers haven't suggested this alternative, so I might as well post it here.

Related