Modules in Python: defaultdict

Prem Vishnoi(cloudvala)
2 min readMay 28, 2023

--

photo by vishnoi

Let’s discover defaultdict and its functions.

We’ll cover the following

  • Overview of defaultdict
  • Simple example of counting the occurrence of words
  • Trying Python list type as default_factory
  • Using lambda as default_factory

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:

Once again, this cuts out the if/else conditional logic and makes the code easier to follow.

Using lambda as default_factory

This is some pretty cool stuff! Let’s go ahead and try using a lambda too as our default_factory!

--

--

Prem Vishnoi(cloudvala)
Prem Vishnoi(cloudvala)

Written by Prem Vishnoi(cloudvala)

Head of Data and ML experienced in designing, implementing, and managing large-scale data infrastructure. Skilled in ETL, data modeling, and cloud computing

No responses yet