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

Let’s put this into a complete example where we count the frequency of each character in a given string.

from collections import Counter

# Input string
my_string = "hello world"

# Create a Counter object
counter = Counter(my_string)

# Display the counts
for char, count in counter.items():
    print(f"Character: {char}, Count: {count}")
from collections import Counter

# Input string
my_string = "hello world"

# Create a Counter object
counter = Counter(my_string)

# Display the counts
print("Character counts:")
for char, count in counter.items():
    print(f"Character: {char}, Count: {count}")

# Most common elements
most_common_chars = counter.most_common(2)
print("\nMost common characters:")
print(most_common_chars)

# Update the counter with another string
counter.update("hello")
print("\nUpdated counts after adding 'hello':")
print(counter)

# Subtract counts of another string
counter.subtract("world")
print("\nCounts after subtracting 'world':")
print(counter)

This example demonstrates how to count characters in a string, find the most common characters, update the counts, and subtract counts using Python’s collections.Counter.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading