Modules in Python: defaultdict

Overview of defaultdict

The collections module has a handy tool called defaultdict. The defaultdict is a subclass of Python’s dict that accepts a default_factory as its primary argument. The default_factory is usually a Python type, such as int or list, but we can also use a function or a lambda.

Simple example of counting the occurrence of words

Let’s start by creating a regular Python dictionary that counts the number of times each word is used in a sentence:

Get hands-on with 1200+ tech skills courses.