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)
Output
{'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))
Output
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"))
Output
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))
Output
[('l', 3), ('o', 2), ('h', 1)]

Common mistakes

  • Calling s.count(ch) inside a loop over s. Each call scans the whole string, so the program becomes O(n²). Count once with a dict or Counter.
  • Writing counts[ch] += 1 on a plain dict. The first time a character appears there is no key yet, so Python raises KeyError. Use .get(ch, 0), Counter or defaultdict(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.

main.py
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).

More Python programs

  • How to remove duplicates from a list in Python

    Remove duplicates from a Python list and keep the original order, with dict.fromkeys, a set and a loop. Run every example in your browser.

  • Palindrome program in Python

    Check if a string or a number is a palindrome in Python with slicing, two pointers and a loop, and ignore spaces and case. Run every example in your browser.

  • Fibonacci series in Python

    Print the Fibonacci series in Python with a for loop, a while loop, recursion and a generator, and find the nth Fibonacci number. Run every example in your browser.

All Python programs Online Python compiler