Counting Letter Frequency in a String (Python)

Kelvin San  picture Kelvin San · Dec 6, 2016 · Viewed 72.7k times · Source

I am trying to count the occurrences of each letter of a word

word = input("Enter a word")

Alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

for i in range(0,26):
    print(word.count(Alphabet[i]))

This currently outputs the number of times each letter occurs including the ones that don't.

How do I list the letters vertically with the frequency alongside it, e.g., like the following?

word="Hello"

H 1

E 1

L 2

O 1

Answer

LMc picture LMc · Dec 6, 2016
from collections import Counter
counts=Counter(word) # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
for i in word:
    print(i,counts[i])

Try using Counter, which will create a dictionary that contains the frequencies of all items in a collection.

Otherwise, you could do a condition on your current code to print only if word.count(Alphabet[i]) is greater than 0, though that would be slower.