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.

Let’s see how defaultdict…


This content originally appeared on DEV Community and was authored by Kathan Vakharia

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


This content originally appeared on DEV Community and was authored by Kathan Vakharia


Print Share Comment Cite Upload Translate Updates
APA

Kathan Vakharia | Sciencx (2021-06-18T16:46:33+00:00) Python’s Collections Module: defaultdict. Retrieved from https://www.scien.cx/2021/06/18/pythons-collections-module-defaultdict/

MLA
" » Python’s Collections Module: defaultdict." Kathan Vakharia | Sciencx - Friday June 18, 2021, https://www.scien.cx/2021/06/18/pythons-collections-module-defaultdict/
HARVARD
Kathan Vakharia | Sciencx Friday June 18, 2021 » Python’s Collections Module: defaultdict., viewed ,<https://www.scien.cx/2021/06/18/pythons-collections-module-defaultdict/>
VANCOUVER
Kathan Vakharia | Sciencx - » Python’s Collections Module: defaultdict. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/18/pythons-collections-module-defaultdict/
CHICAGO
" » Python’s Collections Module: defaultdict." Kathan Vakharia | Sciencx - Accessed . https://www.scien.cx/2021/06/18/pythons-collections-module-defaultdict/
IEEE
" » Python’s Collections Module: defaultdict." Kathan Vakharia | Sciencx [Online]. Available: https://www.scien.cx/2021/06/18/pythons-collections-module-defaultdict/. [Accessed: ]
rf:citation
» Python’s Collections Module: defaultdict | Kathan Vakharia | Sciencx | https://www.scien.cx/2021/06/18/pythons-collections-module-defaultdict/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.