![Python Data Structures and Algorithms](https://wfqqreader-1252317822.image.myqcloud.com/cover/153/36701153/b_36701153.jpg)
defaultdict
The defaultdict object is a subclass of dict and therefore they share methods and operations. It acts as a convenient way to initialize dictionaries. With a dict, Python will throw a KeyError when attempting to access a key that is not already in the dictionary. The defaultdict overrides one method, __missing__(key), and creates a new instance variable, default_factory. With defaultdict, rather than throw an error, it will run the function, supplied as the default_factory argument, which will generate a value. A simple use of defaultdict is to set default_factory to int and use it to quickly tally the counts of items in the dictionary, for example:
![](https://epubservercos.yuewen.com/CC12CE/19470408801644306/epubprivate/OEBPS/Images/4aacc08f-6ac6-4bd8-ba58-b282cf6cec45.png?sign=1739292786-EcD8SUl4Vg47kMs9j9qaGDtzyNKOXBWs-0-556f56d5979c4c30e268d04724e77e1d)
You will notice that if we tried to do this with an ordinary dictionary, we would get a key error when we tried to add the first key. The int we supplied as an argument to default dict is really the function int() that simply returns a zero. We can, of course, create a function that will determine the dictionary's values. For example, the following function returns True if the supplied argument is a primary color, that is red, green, or blue, or returns False otherwise:
def isprimary(c):
if (c == 'red') or (c == 'blue') or (c == 'green'):
return True
else:
return False
We can now create a new defaultdict object and use the isprimary function to populate it:
![](https://epubservercos.yuewen.com/CC12CE/19470408801644306/epubprivate/OEBPS/Images/28788093-ffe4-444d-b88d-61d3a0f176a7.png?sign=1739292786-xnB0oES7KAMnvCasnLdPwkzMVyuvDfJ0-0-57f30c9da7ef8c0c6a47855994502a0c)