All Articles

How to Use Defaultdict in Python?

dict vs defaultdict

defaultdict is a subclass of the dict class.

>>> from collections import defaultdict
>>> issubclass(defaultdict, dict)

The difference between a dict and defaultidict is that defaultdict handles missing values whereas dict throws an exception.

For example, the following code gives a KeyError when we are using a dict:

>>> my_dict = {1: 'One', 2: 'Two'}
>>> my_dict[3]
Traceback (most recent call last):   
  File "<stdin>", line 1, in <module>
KeyError: 3

If we use, defaultdict:

from collections import defaultdict

my_defaultdict = defaultdict(int, {1: 'One', 2: 'Two'})  # the second argument is optional

This code outputs 0. Since here we have passed the datatype as int (this is called default_factory), the missing key takes the value of 0.

If we now try printing my_defaultdict:

>>> print(my_defaultdict)
defaultdict(<class 'int'>, {1: 'One', 2: 'Two', 3: 0})

Note: If we try to instantiate a defaultdict without passing value to default_factory (for example, my_defaultdict = defaultdict()) it will behave as a normal dictionary.

We can also pass list and set as parameters. By default, they default to an empty list and an empty set respectively.


from collections import defaultdict

my_list_defaultdict = defaultdict(list)
my_list_defaultdict[1].append('One')  # defaultdict returns an empty list and we
                                      # are appending to it


This prints an empty list.

Note: A callable-object (or None) must be passed to the initializer of the defaultdict type. For example, defaultdict(0) will throw TypeError.

Passing Arguments Using lambda Functions

We can use a lambda function to pass arguments to defaultdict.


from collections import defaultdict

my_defaultdict = defaultdict(lambda: 'My default')


The above code outputs 'My default'.


from collections import defaultdict

def my_default():
    return 'My default'

my_defaultdict = defaultdict(my_default)


This also prints 'My default'.