A defaultdict
, defined in the collections module, is a data type that is a subclass of the standard dict type. It allows us to set, in advance, a default that will be returned whenever a non-existent key is accessed in the dictionary.
The KeyError
exception is normally raised when you try to acces non-existent keys from a dictionary.
The standard dict
allows us to set default values by utilizing either the get()
or the setdefault
()
method so that the default value is returned rather than raising the KeyError
exception.
The defaultdict
, unlike the standard dict
, allows us to set default value for all keys at instantiation, so that if a key(any) being accessed does not exist in the dictionary, then the default value is returned. This makes it inessential to explicitly specify a default value for each key.
Working with defaultdicts objects
We use the following syntax to create defaultdict
objects.
defaultdict(default_factory = None, mapping = None, iterable = None, **kwargs)
copy
Don't worry much about the syntax it is not as complicated as it seems it is literally the way we initialize standard dictionaries save for the default_factory
parameter.
factory_factory |
This is a function that does not take any argument and should return the default value. This argument should be given as None if no default value is to be specified. |
mapping |
Used in case where we are initializing the defaultdict with a mapping such as a standard dictionary. |
iterable |
Used in case when we are initializing the defaultdict with an iterable containing key-value pairs. |
**kwargs |
Used when we are initializing the defaultdict using the key = value syntax. |
As mentioned above, you should set the default_factory
argument to None
, if no default value is to be specified. Note that if the default_factory
is None
, the KeyError
exception will be raised as usual.
Lambda functions as default_factory functions
Since lambda functions can be defined in-line, they makes good choices for generating default values.
defaultdict methods
Since defaultdict
class is derived from the standard dict
type, it supports the same methods and operations as the dict class.