defaultdict explained
If we wanted to count occurrences in a list (without collections.Counter) we could write this:
res = {} for x in xs: res[x] = res.get(x, 0) + 1
Alternatively, we could use a defaultdict. The constructor of a defaultdict takes one arg – a function – what to do when a new key is added to the dict. So instead, you could write:
from collections import defaultdict res = defaultdict(lambda: 0) for x in xs: d[x] += 1
But the final addition that makes it briefer but perhaps more confusing on first approach is that defaultdict understands int to mean the same as lambda: 0 and has the same effect. I.e.
res = defaultdict(int)