counting letters in a string python

count, counter, dictionary, list, python

Solution

I recommend the `collections` module's `Counter` if you're in Python 2.7+

>>> import collections
>>> s = 'a word and another word'
>>> c = collections.Counter(s)
>>> c
Counter({' ': 4, 'a': 3, 'd': 3, 'o': 3, 'r': 3, 'n': 2, 'w': 2, 'e': 1, 'h': 1, 't': 1})

You can do the same in any version Python with an extra line or two:

>>> c = {}
>>> for i in s: 
...     c[i] = c.get(i, 0) + 1

This would also be useful to check your work.

To sort in alphabetical order (the above is sorted by frequency)

>>> for letter, count in sorted(c.items()):
...     print '{letter}: {count}'.format(letter=letter, count=count)
... 
 : 4
a: 3
d: 3
e: 1
h: 1
n: 2
o: 3
r: 3
t: 1
w: 2

or to keep in a format that you can reuse as a dict:

>>> import pprint
>>> pprint.pprint(dict(c))
{' ': 4,
 'a': 3,
 'd': 3,
 'e': 1,
 'h': 1,
 'n': 2,
 'o': 3,
 'r': 3,
 't': 1,
 'w': 2}

Finally, to get that as a list:

>>> pprint.pprint(sorted(c.items()))
[(' ', 4),
 ('a', 3),
 ('d', 3),
 ('e', 1),
 ('h', 1),
 ('n', 2),
 ('o', 3),
 ('r', 3),
 ('t', 1),
 ('w', 2)]

Problem

I have to write a function, `countLetters(word)`, that takes in a word as argument and returns a list that counts the number of times each letter appears. The letters must be sorted in alphabetical order. This is my attempt: ``` def countLetters(word): x = 0 y = [] for i in word: for j in range(len(y)): if i not in y[j]: x = (i, word.count(i)) y.append(x) return y ``` I first tried it without the `if i not in y[j]` ``` countLetters("google") ``` result was ``` [('g', 2), ('o', 2), ('o', 2), ('g', 2), ('l', 1), ('e', 1)] ``` when I wanted ``` [('e', 1), ('g', 2), ('l', 1), ('o', 2)] ``` When I added the `if i not in y[j]` filter, it just returns an empty list []. Could someone please point out my error here?

Original source