Some of the responses are outdated, here's one of the things that is now part of python:
Python 2.5 introduced defaultdict in the collections module:
from collections import defaultdict
d = defaultdict(int)
d['foo'] +=1 # look ma! no error!
For this application, if you're using Python 2.7 there's now a Counter in collections, you can do the same as above, just call Counter(). You can also do:
c = Counter(iter) # iter is an iterable. It will count the elements!
Comments
Some of the responses are outdated, here's one of the things that is now part of python:
Python 2.5 introduced defaultdict in the collections module:
For this application, if you're using Python 2.7 there's now a Counter in collections, you can do the same as above, just call Counter(). You can also do: