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:
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: