Python – DefaultDict Object. Or how to avoid the Key Error.

Have you seen the error below?

Of course you have. And you know, that it is because you have written something extremely unwise like this:

Yeah. You cannot increment the value of a non-existent key. Unless…

Sun, football and basketball. In this order.

Unless you do not decide to use the default dictionary object – https://docs.python.org/3/library/collections.html?highlight=defaultdict#collections.defaultdict

Then you can nicely increment anything, without caring whether it exists. And instead of having a key error on the example above, you will have a simple 5. Let’s see the example:

This is what we will get as a result:

That’s all! Enjoy it! 🙂

Tagged with: , ,