Skip to content

Python Counter string

  • by

Python counter can be used to calculate the frequency in a string because the string is passed as input. it returns the output as a dictionary having keys that are the unique elements of the list and values are the corresponding frequencies of the elements.

Python Counter string

Simple example code.

from collections import Counter

s = 'ABCAB'
d = Counter(s)

# print Counter value
print(d)

# access the values corresponds to each keys of the returned dictionary
print(d.values())

# get the keys and values both of dictionary
print(d.items())

# get only the keys
print(d.keys())

# sort the values of dictionary
print(sorted(d))

Output:

Python Counter string

Update Counter collection in python with string, not letter

You can update it with a dictionary since adding another string is the same as updating the key with the count.

from collections import Counter

c = Counter(['black', 'blue'])

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

Output: Counter({‘black’: 1, ‘blue’: 1, ‘red’: 1})

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

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

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

Do comment if you have any doubts or suggestions on this Python counter topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *