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
works,
Importing defaultdict
Importing defaultdict
is same as in case of Counter
, just make sure about the capitalization.
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
We can simplify the above process using a lambda function.
🦜 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
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)