Using Defaultdict in Python

Dictionaries are a great convenient way to store and retrieve data by name in python.

>>> mydict = { 'first_name' : 'Rakesh', 'last_name': 'Gautam' }
>>> print(mydict['first_name'])
Rakesh
>>> print(mydict['last_name'])
Gautam

But if you try to get an item with a key that is not currently in the dictionary, Regular Python dictionary raises a KeyError exception.

>>> print(mydict['middle_name'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'middle_name'

While this is easy to handle manually, the defaultdict simplifies this kind of task.

DefaultDict works exactly like a regular python Dict, but it is initialized with a function, that takes no argument and provides a default value for a non-existent key.

DefaultDict never raises a KeyError exception. If any key does not exist, its value gets returned by the DefaultDict.

DefaultDict is part of the python’s collections package.

>>> from collections import defaultdict

>>> mydict = { 'first_name' : 'Rakesh', 'last_name': 'Gautam' }
>>> def_dict = defaultdict(str, mydict)
>>> print(def_dict['first_name'])
Rakesh
>>> print(def_dict['middle_name'])

>>>

Here, this didn’t raise any KeyError exception because we passed str as an argument to the defaultdict.

def_dict returns "" (default value for string) here if we pass a non-existant key as an argument.

>>> my_dict = {'a' : 10, 'b': 20, 'c':30}

>>> dict_2 = defaultdict(lambda : 0, my_dict)
>>> print(dict_2['x'])
0

Here, we passed lambda : 0 as a function to defaultdict, and this will return 0, whenever we ask for a non-existent key.

We can use any function that takes no argument, in the defaultdict. If someone attempts to access a key to which no value has been assigned, that function will be called (without arguments) and its return value is used as the default value for the key.