From Grokking Defaultdict to Solving Graph Problems (Part 1)

Rafat Ashraf Joy
The Startup
Published in
3 min readSep 11, 2020

This article provides a beginner suitable intro to defaultdict module of collections. The author assumes that you are familiar with dict in python.

What is the difference between defaultdict and dict? A defaultdict works exactly the same way a normal dict does, but it is initialized with a callable function called default_factory() that takes no arguments and provides a default value for a non-existent key.

Let’s look at a fancy example. Imagine in an office the salary of nearly every employee is 5000 $. But some experienced employees get a different amount which is specified by the manager.

The output of the code snippet would look like :

6000
7000
5000

Note that we previously didn’t add any key named Cooley in the dictionary named “salary”.

So, what is going inside?

If we had done the same with the general dictionary, then it would raise a key error like this :

error message if used dict

Now, what is defaultdict doing? It is assigning a default value to any unassigned new key of the dictionary by a function.

default function

As we didn’t define any key named “Cooley”, the defaultdict assigned the default value i.e the value we declared in function “func” above. This is the speciality of defaultdict and this feature very often comes handy while working with graph problems.

To sum up: defaultdict provides a default value for the key that does not exist. Thus the key error is averted.

Let us look at another example to make this even clearer. Imagine we need to need to make a lookup table named menu where the key is the country’s name and the value is the list of foods originated in this country. The key will be a string and the value will be a list.

from collections import defaultdictmenu = defaultdict(list)menu['Italy']=['Pizza','Pasta']
menu['Mexico']=['Taco']
menu['Japan']=['Ramen']
print(menu['Italy'])
print(menu['Mexico'])
print(menu['Japan'])
print(menu['Iceland'])
print(menu['Poland'])

The output will be as follows :

['Pizza', 'Pasta']
['Taco']
['Ramen']
[]
[]

Note that we did not define any key named ‘Iceland’ and ‘Poland’ in the menu defaultdict.

In line 2 of the code snippet, we defined the default function as an empty list. i.e. :

menu = defaultdict(list)

So any key that was not assigned before will show an empty list as default value.

--

--

Rafat Ashraf Joy
The Startup

Computer Science PhD Student at University of Illinois Chicago