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.

Leave a Comment