defaultdict explained

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

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *