I myself being from the ‘; {}’ world, Python has amused me so many times with it’s wacky way of getting things done. But I would like to call that ‘wacky way’ as ‘Pythonic way’ And Hence the name of series. We will talk about all the peculiar aspect of Python in this series. These built in methods are both elegant and optimized in nature. We should use as much as possible in our code to improve readability and efficiency of code. Coming back to the point, We are going to talk about defaultdict — enhanced version( subclasse) of dictionary type in python.

Little background.

Dictionary in python are collections of item/python object. Unlike other containers, with values only, dictionary contains key:value pair.

Dictionary itself is a mutable object and so are values in key:value pair but key for such value must be immutable python object.

See Also: Immutability in python

Generally, keys are string. But we can use any other immutable object. And like index in list, keys are used in dictionary to retrieve corresponding values.

Likewise, we can use key with assignment operator to create/update key:value pair.

But what happens if we use non-existing key?

It raises a KeyError. This is where defaultdict comes handy.

What exactly is defaultdict?

When key is not found in defaultdict instead of throwing KeyError defaultdict initializes the given key. And value for that key is assigned as returned value from default_factory or callable. Let’s see an example to make things clear.

Here, Line 5 initializes an empty instance of defaultdict with int as default_factory. New keys are assigned value returned by callable after calling it. More about callable could be found in this link

Let’s see if new key has been created or not.

Unlike in normal dictionary, new key height is created without using assignment operator. We can see the value 0 because calling int() function returns 0.

What else could be used as callable?

An instance of a class with a __call__ method or any other function/ method can be used as callable in defaultdict. Let’s define our own function and use it as argument.

We can use anonymous lambda function as well.

Till now it looks nothing important right? Let’s see some real use case.

Some example

  1. Word count problem from official doc: Let’s say we have to store alphabet count in dictionary like this.

One way of doing this would be.

Pythonic Way

If we use other callable like list, dict as callable, then we can use methods of those callable like:

Bonus Point: You can define nested defaultdict as:

Use of partial is preferred over lambda . We will see why in our next post.