Python Collections — DefaultDict : Dictionary with Default values and Automatic Keys

Deepak K [Daksh] Gupta
May 21 · 5 min read
Image for post
Image for post
Python Collections — DefaultDict

Intro & Prerequisite

This post is about Python Programming Language. This post talks about Python Collections and you need to have a minimal understanding of python to understand the same. If you’re new to python, I’ll highly recommend you reading my other posts, especially Object Oriented Python Classes & Objects

Python Collections — What are they?

Python Collections are specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.

These alternatives are not a replacement of built-in types, but provides additional mechanisms which not only handles some of the obvious scenarios, but may also help you to write less lines of codes.

Recap — Python Dict

Python 'dict’ is an associative container / data structure with Key Value pair(s).

If you’re coming from another language like C++ or Java, you can relate python dictionary to maps

So What exactly is DefaultDict?

defaultdict is a dict for all practical purpose. You don’t need to learn new syntax or understand anything special to start using dict.

defaultdict is dict with Default Values where you’ll never get a KeyError

To properly understand the same, let’s see a simple example of the dict

Image for post
Image for post
Creating a dictionary and accessing a key which is not in the dictionary

When we run this code, we’ll get the following error

KeyError: 'key - 1'

Because the key key — 1 is not present in the dictionary a_dct and this error is obvious and reasonable. However, we’d not like our code to fail, so we’ll have to handle this error with one of the following ways

Image for post
Image for post
Handling `Key Error` using dictionary

With defaultdict, you don’t need to worry about handling this error scenario because this condition will never come

defaultdict does a couple of things

  1. When it is accessed, if the key is not present in the dictionary, it will create the key so no chance of Key Error
  2. While creating defaultdict, you need to provide a default value which will be assigned to the key automatically created (step — 1 above). However, the key has to be provided as a callable (a function which returns a value) and not as a raw value.

Here is how we can use defaultdict instead of dict for the above example

Image for post
Image for post
Simple Example of defaultdict

Is this the only difference between dict and defaultdict ?

Good Question…!!!

The short answer is “Yes”

long answer is Yes, but we can use callable (the function which we provide which creating the defaultdict) using multiple built-in types where defaultdict perform better that plain dictionary

For example, here is the default values when we create defaultdict with int, float, and str

a_dct = defaultdict(int)   # The Default Value is "0"a_dct = defaultdict(float)   # The Default Value is "0.0"a_dct = defaultdict(str)   # The Default Value is ""

Which effectively means that for any keys with values, we will get default values automatically.

We can also use defaultdict with the list, tuple or with another dict itself. Let’s see how to make use of it

Using defaultdict with list

When we create defaultdict with list, we can blindly use list functions like append on any key whether or not it is exists. Here is an example of the same

Image for post
Image for post
Defaultdict with list

Using defaultdict with tuple

Just like list we can use tuple as a default values. Since tuples are immutable, we can’t append in it as we’re doing it with list, however, we can replace complete tuple for a key.

Here is a simple example of the same

Image for post
Image for post
defaultdict with tuple

Using defaultdict with dict

It looks weird at first, but we can create a defaultdict with dict too. Heer is a simple example of the same

Image for post
Image for post
Defaultdict with dict

And believe me, defaultdict with dict are being used widely.

Is there anything I should be extremely careful about?

Yes, even if you create a defaultdict with list, tuple, int, float etc, you can overwrite and assign it to something totally different. If this happens, then most of your code will fail.

Here is a simple example of the same

Image for post
Image for post
What NOT to do with defaultdict

Even if you decided to use a particular default value for defaultdict, you can replace the value or keys at any point of time and you MUST never do that. There is nothing wrong in it syntactically, but this is not the reason for using defaultdict, and you must use other constructs for writing your code

That’s all for this post, Hope I was able the explain defaultdict in an easy and intuitive way.

Thanks for reading…!!!!

Daksh

The GitHub link for the code is present @ https://github.com/CodesBay/Modern-Python-Programming/tree/master/Python%20DefaultDict

Here is my YouTube video on the same topic

My YouTube Video on Python Collection — The DefaultDict

The Startup

Medium's largest active publication, followed by +716K people. Follow to join our community.

Deepak K [Daksh] Gupta

Written by

Software Crafter | Tech Speaker | Content Creator, YouTuber & Bloggers | linkedin.com/in/dakshhub/ | bit.ly/CodesBay | bit.ly/DeepakKDaksh | https://bit.ly/d_in

The Startup

Medium's largest active publication, followed by +716K people. Follow to join our community.

Deepak K [Daksh] Gupta

Written by

Software Crafter | Tech Speaker | Content Creator, YouTuber & Bloggers | linkedin.com/in/dakshhub/ | bit.ly/CodesBay | bit.ly/DeepakKDaksh | https://bit.ly/d_in

The Startup

Medium's largest active publication, followed by +716K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store