Count how many times each character appears in a string in Python
Count the frequency of each character in a Python string with a dict, collections.Counter and str.count, and find the most common one. Run it in your browser.
Short answer
Loop over the string and add one to a dictionary: counts[ch] = counts.get(ch, 0) + 1. Or use collections.Counter(s), which does the same in one line and gives you most_common().
Method 1: a dictionary with .get
counts.get(ch, 0) returns the current count, or 0 the first time a character appears, so one line handles both cases. This is the most useful dictionary pattern in Python.
word = "banana"
counts = {}
for ch in word:
counts[ch] = counts.get(ch, 0) + 1
print(counts)
{'b': 1, 'a': 3, 'n': 2}Method 2: collections.Counter
Counter is a dictionary built for counting. most_common(k) returns the k highest counts, largest first.
from collections import Counter
counts = Counter("banana")
print(counts)
print(counts.most_common(1))
Counter({'a': 3, 'n': 2, 'b': 1})
[('a', 3)]Method 3: count one character with str.count
When you only need one character, the string method is enough.
print("banana".count("a"))
3
Method 4: ignore spaces and capital letters
Filter while you count: lowercase the text and keep only letters.
from collections import Counter
text = "Hello World"
counts = Counter(ch for ch in text.lower() if ch.isalpha())
print(counts.most_common(3))
[('l', 3), ('o', 2), ('h', 1)]Common mistakes
- Calling
s.count(ch)inside a loop overs. Each call scans the whole string, so the program becomes O(n²). Count once with a dict orCounter. - Writing
counts[ch] += 1on a plain dict. The first time a character appears there is no key yet, so Python raisesKeyError. Use.get(ch, 0),Counterordefaultdict(int). - Counting spaces and punctuation by accident. Filter with
ch.isalpha()if you want letters only.
Practice: your turn
Write solve(s) that returns the most frequent character of s. If two characters tie, return the one that appears first in s.
This challenge and its tests come from the PyMaster course. Press Run tests to check your function.
Input for input()
Runs real Python 3.14 in your browser with Pyodide. Your code is not uploaded. Ctrl + Enter runs the tests. Press Esc, then Tab, to leave the editor.
Hint 1
Build counts with counts.get(ch, 0) + 1.
Hint 2
Keep two trackers: the best character and its count. When a count beats the best, replace both.
Hint 3
Loop over counts.items() in order; a strict greater-than check keeps the first-seen winner on ties.
Show a solution
def solve(s):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
best, best_count = None, 0
for ch, n in counts.items():
if n > best_count:
best, best_count = ch, n
return best
Questions
How do I find the most common character in a string?
Counter(s).most_common(1)[0][0]. With a plain dict, max(counts, key=counts.get) does the same and returns the first one on a tie.
How do I count words instead of characters?
Split first: Counter(text.split()). Lowercase the text if “The” and “the” should count as one word.
Does the dictionary keep the order of the characters?
Yes. Since Python 3.7 a dict keeps the order keys were first added, so the counts come out in the order the characters first appear.
How do I print the counts one per line?
Loop over the items: for ch, n in counts.items(): print(ch, n).
