Count Character Frequency in Python

Counting how many times each character appears in a string is a fundamental problem with many real-world applications, from text analysis to compression algorithms.

Best Solution: Using Counter

from collections import Counter

def char_frequency(s):
    return Counter(s)

result = char_frequency("hello world")
print(result)
# Output: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

Most Common Characters

from collections import Counter

s = "programming"
freq = Counter(s)
print(freq.most_common(3))
# Output: [('g', 2), ('r', 2), ('m', 2)]

Manual Approach Using a Dictionary

def char_frequency_manual(s):
    freq = {}
    for char in s:
        freq[char] = freq.get(char, 0) + 1
    return freq

print(char_frequency_manual("banana"))
# Output: {'b': 1, 'a': 3, 'n': 2}

Using get() with Default

s = "mississippi"
freq = {}
for ch in s:
    freq[ch] = freq.get(ch, 0) + 1

print(freq)
# Output: {'m': 1, 'i': 4, 's': 4, 'p': 2}

Key Takeaway

Counter from the collections module is the cleanest and most powerful solution. It also provides handy methods like most_common() for quick analysis.

(Visited 1 times, 1 visits today)