Python tip 17: counting frequency of items
One of the ways to count the frequency of items is to make use of the dict.get()
method:
>>> vehicles = ['car', 'jeep', 'car', 'bike', 'bus', 'car', 'bike']
>>> hist = {}
>>> for v in vehicles:
... hist[v] = hist.get(v, 0) + 1
...
>>> hist
{'car': 3, 'jeep': 1, 'bike': 2, 'bus': 1}
And here's a solution using the built-in collections module:
>>> from collections import Counter
>>> vehicles = ['car', 'jeep', 'car', 'bike', 'bus', 'car', 'bike']
>>> Counter(vehicles)
Counter({'car': 3, 'bike': 2, 'jeep': 1, 'bus': 1})
>>> Counter('abracadabra')
Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
See stackoverflow: using a dictionary to count items and stackoverflow: count frequency of elements for more ways to solve this problem.
Video demo:
See also my 100 Page Python Intro ebook.