Get the number of occurrences of each character

Given the string:

a='dqdwqfwqfggqwq'

How do I get the number of occurrences of each character?


In 2.7 and 3.1 there's a tool called Counter:

>>> import collections
>>> results = collections.Counter("dqdwqfwqfggqwq")
>>> results
Counter({'q': 5, 'w': 3, 'g': 2, 'd': 2, 'f': 2})

Docs. As pointed out in the comments it is not compatible with 2.6 or lower, but it's backported.


Not highly efficient, but it is one-line...

In [24]: a='dqdwqfwqfggqwq'

In [25]: dict((letter,a.count(letter)) for letter in set(a))
Out[25]: {'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}