Python Program to Count Character Frequency in a String
freq[ch] = freq.get(ch, 0) + 1, or simply use Counter(text).A character frequency table answers the question "how many times does each character appear?". It is the basis of anagram checks, simple ciphers and text statistics, and it is the best beginner example of using a dictionary as a counter.
Below you will build the table by hand, see how collections.Counter shortens it, and learn how to print it in a predictable order.
| Input | A string such as "banana" |
|---|---|
| Output | A dictionary mapping each character to its count |
| Approach | Walk through the string and increase a dictionary count for each character |
| Time complexity | O(n) time, O(k) space for k distinct characters |
Approach to count character frequency step by step
- Start with an empty dictionary,
freq = {}. - Loop over each character of the string.
- Read the current count with
freq.get(ch, 0), which gives 0 for a character not seen yet. - Store the count plus one back under that character.
- After the loop,
freqholds the answer. Dictionaries keep insertion order, so characters appear in the order they were first seen.
How the frequency code works
The key line is freq[ch] = freq.get(ch, 0) + 1. Without the default, a new character would raise a KeyError, because the key does not exist yet; dict.get() avoids that.
Spaces and punctuation are characters too. If you only care about letters, add if ch.isalpha() to the loop, and call lower() first when "A" and "a" should be counted together.
freq = {}
for ch in "banana":
freq[ch] = freq.get(ch, 0) + 1
print(freq)Other ways to get letter counts
Counter(text) from the collections module does the whole loop for you and adds most_common(). str.count(ch) also works, but calling it for each distinct character rescans the string every time. To print the table in a stable order, loop over sorted(freq.items()); this is the safest habit when the output must be reproducible.
| Method | Code | When to use |
|---|---|---|
| Manual dictionary | freq[ch] = freq.get(ch, 0) + 1 | Learning how counting works |
Counter | Counter(text) | Everyday use, needs most_common() |
str.count() | {c: text.count(c) for c in set(text)} | Very short strings only |
Examples you can run
Press Run, then edit the code and run it again.
Build a frequency dictionary
Count every character, including repeated ones.
text = "programming"
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
print(freq)Expected output{'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}
Counter and most_common
Counter gives the same result and ranks the characters.
from collections import Counter
counts = Counter("mississippi")
print(dict(counts))
print(counts.most_common(2))Expected output{'m': 1, 'i': 4, 's': 4, 'p': 2}
[('i', 4), ('s', 4)]
Letters only, printed in sorted order
Ignore spaces and punctuation, and print one line per letter.
text = "Hello, World!"
freq = {}
for ch in text.lower():
if ch.isalpha():
freq[ch] = freq.get(ch, 0) + 1
for letter, count in sorted(freq.items()):
print(letter, count)Expected outputd 1
e 1
h 1
l 3
o 2
r 1
w 1
Edge case: empty string
An empty string produces an empty dictionary.
from collections import Counter
print(dict(Counter("")))Expected output{}
Interactive version
Read a word and print its table.
word = input("Enter a word: ")
freq = {}
for ch in word:
freq[ch] = freq.get(ch, 0) + 1
for ch, n in freq.items():
print(f"{ch}: {n}")Expected outputEnter a word: apple
a: 1
p: 2
l: 1
e: 1
Common mistakes
Incrementing a missing key
✗ Wrong
freq = {}
for ch in "abc":
freq[ch] += 1✓ Right
freq = {}
for ch in "abc":
freq[ch] = freq.get(ch, 0) + 1
print(freq)Give new keys a starting value with freq.get(ch, 0) + 1, or use Counter.
Printing a set of characters in a fixed order
✗ Wrong
print(set("hello"))✓ Right
print(sorted(set("hello")))Use sorted() when output order matters.
Python Program to Count Character Frequency in a String: questions people ask
How do I count the frequency of characters in a string in Python?
Use collections.Counter(text), or loop and update a dictionary with freq[ch] = freq.get(ch, 0) + 1.
How do I find the most frequent character?
Call Counter(text).most_common(1), which returns a list with the character and its count. With ties, the character seen first comes first.
Should spaces be counted?
Only if you want them. Spaces are ordinary characters, so skip them with if ch != " " or keep only letters with ch.isalpha().
Keep learning
Step-by-step lessons:
Python DictionariesPython collections ModulePython for Loops
Related:
Python Word Count Program: Count Words in a StringPython Program to Count Vowels in a StringPython Anagram Program: Check if Two Strings Are AnagramsPython Dictionary get() MethodPython String count() Method
More in string programs:
Python Program to Check Palindrome (String and Number)Python Program to Count Vowels in a StringPython Anagram Program: Check if Two Strings Are AnagramsPython Word Count Program: Count Words in a String See all →