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
for ch in wordgives one character at a time:m,i,s,s, and so on.counts.get(ch, 0)is the count so far, or 0 the first time a character is seen. Adding 1 and storing it back updates the count.- The keys appear in the order each character was first seen in the word.
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: 0ch.isalpha()keeps only letters, so the comma and the space are not counted.lower()makesHandhthe same.- Asking a
Counterfor a missing key gives 0, not aKeyError. A normal dictionary would raise the error. - When counts are equal,
most_common()keeps the order in which the characters were first seen. That is whyhcomes beforee,w,randd.
Related programs: Find the most frequent character in a string.