Rohit
Rohit

Reputation: 3157

Counting each letter's frequency in a string

This is a question from pyschools.

I did get it right, but I'm guessing that there would be a simpler method. Is this the simplest way to do this?

def countLetters(word):
    letterdict={}
    for letter in word:
        letterdict[letter] = 0
    for letter in word:
        letterdict[letter] += 1
    return letterdict

This should look something like this:

>>> countLetters('google')
{'e': 1, 'g': 2, 'l': 1, 'o': 2}

Upvotes: 19

Views: 48313

Answers (2)

Cat Plus Plus
Cat Plus Plus

Reputation: 129994

In 2.7+:

import collections
letters = collections.Counter('google')

Earlier (2.5+, that's ancient by now):

import collections
letters = collections.defaultdict(int)
for letter in word:
    letters[letter] += 1

Upvotes: 49

mata
mata

Reputation: 69092

>>> import collections
>>> print collections.Counter("google")
Counter({'o': 2, 'g': 2, 'e': 1, 'l': 1})

Upvotes: 16

Related Questions