DEV Community 👩‍💻👨‍💻

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

Posted on

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)!

Top comments (0)

Hacktoberfest is happening now!



It is a month-long celebration of open source. For a lot of devs, its their introduction to open source.


Check out the Hacktoberfest tag on DEV to keep up with the latest!