Counting Letter Frequency in a String (Python)

Counting Letter Frequency in a String (Python)

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.

def char_frequency(str1):
    dict = {}
    for n in str1:
        keys = dict.keys()
        if n in keys:
            dict[n] += 1
        else:
            dict[n] = 1
    return dict
print(char_frequency(google.com))

Counting Letter Frequency in a String (Python)

As Pythonista said, this is a job for collections.Counter:

from collections import Counter
print(Counter(cats on wheels))

This prints:

{s: 2,  : 2, e: 2, t: 1, n: 1, l: 1, a: 1, c: 1, w: 1, h: 1, o: 1}

Leave a Reply

Your email address will not be published. Required fields are marked *