June 2019
Beginner to intermediate
770 pages
19h 24m
English
One of the most common use cases for a defaultdict class is when accumulating counts of key instances. A simple way to count keys looks like this:
frequency = defaultdict(int)
for k in some_iterator():
frequency[k] += 1
This example counts the number of times each key value, k, appears in the sequence of values from some_iterator().
This use case is so common that there's a variation on the defaultdict theme that performs the same operation shown in the preceding code–it's called Counter. A Counter collection, however, is considerably more sophisticated than a simple defaultdict class.
Here's an example that creates a frequency histogram from some source of data showing values in descending order by frequency:
from ...
Read now
Unlock full access