Python Friday #209: Defaultdict

When we work with dictionaries that contains lists, we need to make sure that the list exists before we can add items. Or when we use a dictionary for counters, we must make sure that we have a value before we can increment it. While this can be done by hand, there is a much more elegant way in Python.

This post is part of my journey to learn Python. You find the code for this post in my PythonFriday repository on GitHub.

 

The manual way

We cannot append a value to a non-existent list. Therefore, we must check if the key exists in a dictionary and only append if that is the case. If there is not yet an entry for that key, we need to create a new list with our value:

 

Defaultdict with lists

The defaultdict creates us an empty list for every key that we add to our dictionary. We can directly append without the need to check if the key exists or manually create that list:

We can work with the defaultdict as we do with a regular dictionary for everything else than adding new keys.

 

Defaultdict with numbers

We can also create a defaultdict with integers, which gives us a 0 as the default value for every newly added key:

This is much simpler than the regular way with creating a method to make sure there is a value before we increment it:

 

Next

Using a defaultdict instead of a regular dictionary allows us to directly work with new keys without first making sure that the dictionary contains a (default) value. It saves us a little bit of code, but even that small function could contain bugs that slow us down. Therefore, try defaultdict if you need to work with default values in dictionaries.

Next week we explore a way that can speed-up our applications by caching function calls.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.