October 15, 2024

Python DefaultDict – Ability to assign default values to your keys

Spread the love

A common problem with Python dictionaries is trying to access or modify a key that doesn’t exist. If we try to access or modify a key that doesn’t exist, Python raises a KeyError and breaks up the code execution. There are methods to handle these situations in the standard dictionary library, like using .setdefault() or .get() or using try and except block. But a dictionary-like class is also available in the collections module called defaultdict.

defaultdict behaves almost exactly like a regular Python dictionary, but if we try to access or modify a missing key, then defaultdict will automatically create the key and assign a default value for it. The default value can be a valid Python callable or None. defaultdict is a subclass of dict, which means it inherits from dict. defaultdict overrides the “.__missing__()” method and adds a .default_factory, a writable instance variable that needs to be provided at the time of instantiation.

Let’s look at the syntax for defaultdict

ParameterDescription
default_factoryThis attribute is used by the __missing__() method; it is initialized from the first argument to the constructor, if present, or to None, if absent.
__missing__(key)If the default_factory attribute is None, this raises a KeyError exception with the key as an argument.
If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.
If calling default_factory raises an exception this exception is propagated unchanged.
This method is called by the __getitem__() method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__().
Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.

Using the defaultdict

Let’s create a simple default dict and see what happens when we try to access or modify a missing key

from collections import defaultdict
def_dict = defaultdict(list)
def_dict['one'] = 1
>>> def_dict
defaultdict(<class 'list'>, {'one': 1})

def_dict['missing']
>>> def_dict
defaultdict(<class 'list'>, {'one': 1, 'missing': []})

def_dict['another_missing'] = 'Test'
>>> def_dict
defaultdict(<class 'list'>, {'one': 1, 'missing': [], 'another_missing': 'Test'})
  • We can see that accessing a missing key, adds that key and sets the default value for that key.
  • Also, when we modify a missing key, that key is instead added to the defaultdict.

When to use defaultdict instead of dict

  • When the code is based on dictionaries a lot and we are dealing with missind key pretty often.
  • If you need to initailize the dictionary with a default value.
  • If you rely on dictionaries for aggreagting, counting or grouping values, and performance is a concer.

Hopefully, this article gave you a brief introduction to defaultdict and how it differs from the regular dict.


Spread the love

3 thoughts on “Python DefaultDict – Ability to assign default values to your keys

Leave a Reply

Your email address will not be published. Required fields are marked *