The Python dictionary, dict
, contains words and meanings as well as key-value pairs of any data type. The defaultdict
is another subdivision of the built-in dict
class.
defaultdict
different?The defaultdict
is a subdivision of the dict
class. Its importance lies in the fact that it allows each new key to be given a default value based on the type of dictionary being created.
A defaultdict
can be created by giving its declaration an argument that can have three values; list, set or int. According to the specified data type, the dictionary is created and when any key, that does not exist in the defaultdict
is added or accessed, it is assigned a default value as opposed to giving a KeyError
.
The first code snippet below shows a simple dictionary and how when a key that does not exist in the dict
is accessed, it gives an error.
dict_demo = dict()print(dict_demo[3])
Now let’s introduce a defaultdict
and see what happens.
Note: The
defaultdict
must be imported from thecollections
library.
from collections import defaultdictdefaultdict_demo = defaultdict(int)print(defaultdict_demo[3])
In this case, we have passed int as the datatype to the defaultdict
. Hence, any key that does not already exist in defaultdict_demo
will be assigned a value of 0, unless a value is defined for it.
Now that we have seen how a defaultdict
works and what happens when it is given an int argument, let’s see what happens with the other two parameters.
This results in a dictionary of sets being formed. Hence, given that the same key has two different values, they are assigned to the key as a set of values. An empty key, three
, is simply assigned an empty set.
from collections import defaultdictdefaultdict_demo = defaultdict(set)defaultdict_demo['one'].add(1)defaultdict_demo['two'].add(2)defaultdict_demo['one'].add('1')defaultdict_demo['three']print(dict(defaultdict_demo.items()))
This results in the creation of a dictionary of lists. We use the same example as above, to see what difference exists. There are two:
First, the key with no value is now assigned an empty list upon entry. Moreover, all values are now stored in a list format.
Second, to add elements to the defaultdict
we know use the append
function which is used for lists.
from collections import defaultdictdefaultdict_demo = defaultdict(list)defaultdict_demo['one'].append(1)defaultdict_demo['two'].append(2)defaultdict_demo['one'].append('1')defaultdict_demo['three']print(dict(defaultdict_demo.items()))
Free Resources