PythonMastery

Count character frequency in Python

Count how many times each character appears in a string, first with a plain dictionary and then with collections.Counter and most_common().

A string is a sequence of characters, so you can loop over it and count each character in a dictionary.

The program

python
word = "mississippi"

counts = {}
for ch in word:
    counts[ch] = counts.get(ch, 0) + 1

print(counts)
output
{'m': 1, 'i': 4, 's': 4, 'p': 2}

How it works

Another way: Counter

collections.Counter counts any sequence in one step. most_common(n) returns the n largest counts as (character, count) pairs:

python
from collections import Counter

sentence = "Hello, World"
counts = Counter(ch for ch in sentence.lower() if ch.isalpha())

print(counts.most_common(3))
print("Times 'z' appears:", counts["z"])
output
[('l', 3), ('o', 2), ('h', 1)]
Times 'z' appears: 0

Related programs: Find the most frequent character in a string.

Learn the idea: Dictionaries, Working with Strings, collections: The Stdlib's Hidden Power

A longer explanation: Count anything with collections.Counter