If we wanted to count occurrences in a list (without collections.Counter) we could write this:

1 2 3 |
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:

1 2 3 4 |
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.

1 |
res = defaultdict(int) |