Learning about defaultdict in Python

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.


How is 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.

Let's say we have a defaultdict with datatype int
1 of 3

Example

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 the collections library.

from collections import defaultdict
defaultdict_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.


What other values can it have?

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.

1. Giving set as the parameter

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 defaultdict
defaultdict_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()))

2. Giving list as a parameter

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 defaultdict
defaultdict_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

Copyright ©2024 Educative, Inc. All rights reserved