October 2018
Beginner to intermediate
466 pages
12h 2m
English
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 ...