Update Counter Collection in Python with String, Not Letter

Update Counter Collection in Python with String, Not Letter

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

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})
2
c.update(['red'])
>>> c
Counter({'black': 1, 'blue': 1, 'red': 1})

Source can be an iterable, a dictionary, or another Counter instance.

Although a string is an iterable, the result is not what you expected. First convert it to a list, tuple, etc.

You can use:

c["red"]+=1
# or
c.update({"red": 1})
# or 
c.update(["red"])

All these options will work regardless of the key being present or not. And if present, they will increase the count by 1

1

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

Try this:

c.update({'foo': 1})
3

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.