Python Core Utility - `collections.defaultdict`
dev.to·15h·
Discuss: DEV
Flag this post

Intro

In this post, we will look at the defaultdict datatype from the collections module.

The collections.defaultdict is a subclass of the built-in dict that accepts a callable (default_factory) during its initialization. Then, when you try to access a key in the initialized object, it does a regular dict lookup to fetch the key’s value. If the key is missing, it calls the default_factory that generates a value for the key requested. This key-value pair is then stored in the dict and the value is returned.

Use cases

The primary use case is when you need to build up a dict based on an iterable and don’t want to check if keys exist…

Similar Posts

Loading similar posts...