>>> from collections import defaultdict >>> words = ['a', 'the', 'an', 'a', 'an', 'the'] >>> d = defaultdict(int) >>> for word in words: ... d[word] += 1 ... >>> d defaultdict(<type 'int'>, {'a': 2, 'the': 2, 'an': 2})
In modern Python (starting with Python 2.7, released in 2010), the Pythonic solution is collections.Counter:
>>> from collections import Counter >>> words = ['a', 'the', 'an', 'a', 'an', 'the'] >>> Counter(words) Counter({'a': 2, 'the': 2, 'an': 2})
In modern Python (starting with Python 2.7, released in 2010), the Pythonic solution is collections.Counter:
or dict(Counter(words)) if you want the result to return an actual dict instead of a Counter instance.