defaultdict in Python Makes Your Life Easier
What is a Defaultdict in Python and How do you create a Defaultdict in Python?
Imagine a situation where you want to count the occurence of word in a list. How would you do that?
You’d probably do something like this:
Now, if you have been using dictionaries for a while, you’d understand that it’s not fun to write that “if” condition for when the element is not in the dictionary.
Good news is that we can remove that step by using defaultdict. 🙂
Let’s see how that can be done.
Here, we just removed the “if” part since there’s no need to check if the word is already there in the list.
If the word is already present, it’ll get the default value of 0.
This is how defaultdict in Python makes our lives easier.
defaultdict argument
Keep in mind that defaultdict takes a function as an argument. Here, int is considered a function called “default_factory“ which basically gives (returns) you a default value of zero.
You can also create your own function here that just returns some value.
👉If you liked this post, leave a like ❤️ below. It helps people discover this newsletter on Substack and gives me a feedback on what you like to read.
You can also provide your feedback by leaving a comment. Click on the button below: