DEV Community

Cover image for Python's Collections Module: defaultdict
Kathan Vakharia
Kathan Vakharia

Posted on

1 1

Python's Collections Module: defaultdict

Introduction

It won't surprise you if I tell you it is also a dict subclass :)

defaultdict container type eliminates the chances to get KeyErrors in case of normal dictionaries while accessing non existent keys.
image

Let's see how defaultdict works,

Importing defaultdict

Importing defaultdict is same as in case of Counter , just make sure about the capitalization.
image

Before, we move ahead don't forget it is a dictionary internally so we can leverage all the methods of built-in dict class.

Using defaultdict to provide default values for non-existent keys

image
We can simplify the above process using a lambda function.
image

🦜 Moreover, we can also pass the builtin constructor functions as default_factory argument.

Here, I have passed list which means the default value for any key will be output of list() ➡️ empty list
image

And that's all for the defaultdict container. I hope you are enjoying the series :) If so, leave a like and please comment down below if I've commited any mistake(s)!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay