Update Counter collection in python with string, not letter

aless80 picture aless80 · Jul 27, 2017 · Viewed 13.6k times · Source

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})

Answer

Psidom picture Psidom · Jul 27, 2017

You can update it with a dictionary, since add another string is same as update the key with count +1:

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

c.update({"red": 1})  

c
# Counter({'black': 1, 'blue': 1, 'red': 1})

If the key already exists, the count will increase by one:

c.update({"red": 1})

c
# Counter({'black': 1, 'blue': 1, 'red': 2})