You'd think that you couldn't get much simpler than defaultdict(int), but the I want to count specific instances in an iterable use case is common enough that the Python developers created a specific class for it. The previous code that counts characters in a string can easily be calculated in a single line:
from collections import Counter def letter_frequency(sentence): return Counter(sentence)
The Counter object behaves like a beefed-up dictionary where the keys are the items being counted and the values are the quantities of such items. One of the most useful functions is the most_common() method. It returns a list of (key, count) tuples ordered by the count. You can optionally pass an integer argument into most_common() to request only the top most common elements. For example, you could write a simple polling application as follows:
from collections import Counter responses = [ "vanilla", "chocolate", "vanilla", "vanilla", "caramel", "strawberry", "vanilla" ] print( "The children voted for {} ice cream".format( Counter(responses).most_common(1)[0][0] ) )
Presumably, you'd get the responses from a database or by using a computer vision algorithm to count the kids who raised their hands. Here, we hardcode it so that we can test the most_common method. It returns a list that has only one element (because we requested one element in the parameter). This element stores the name of the top choice at position zero, hence the double [0][0] at the end of the call. I think they look like a surprised face, don't you? Your computer is probably amazed it can count data so easily. It's ancestor, Hollerith's tabulating machine developed for the 1890 US census, must be so jealous!