Python Collections — DefaultDict : Dictionary with Default values and Automatic Keys
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?
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
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.
dictwith Default Values where you’ll never get a
To properly understand the same, let’s see a simple example of the
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
defaultdict, you don’t need to worry about handling this error scenario because this condition will never come
defaultdict does a couple of things
- When it is accessed, if the
keyis not present in the dictionary, it will create the key so no chance of
- 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
Is this the only difference between dict and defaultdict ?
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
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
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
Using defaultdict with tuple
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
Using defaultdict with dict
It looks weird at first, but we can create a
dict too. Heer is a simple example of the same
And believe me,
dict are being used widely.
Is there anything I should be extremely careful about?
Yes, even if you create a
list, tuple, int, floatetc, 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
Even if you decided to use a particular default value for
defaultdict, you can replace the
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…!!!!
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