defaultdict is a subclass of the built-in dict class. Its functionality is the same as that of dict class, expect it allows new key to be given a default value based on the type of dictionary being created.

Syntax

To create defaultdict, use below syntax

collections.defaultdict([default_factory[, …]])

It returns a new dictionary-like object. The first argument provides the initial value for the default_factory attribute. Default value of default_factory is None. Remaining arguments are treated the same as if they were passed to the dict constructor.

Important Methods

In addition to the standard dict operations, defaultdict objects support

  • __missing__(key) : It is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key.
  • default_factory : Initialized from the first argument to the constructor, if present, or to None, if absent. This attribute is used by the __missing__() method.

Default Value in Dict

setdefault() function of regular dictionary sets the default if the key is not present. Below is the syntax for the same

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default.

d = dict()
d.setdefault('missing_key', [])

print(d)
# Output
# {'missing_key': []}

d['missing_key'].append(2)

print(d)
# Output
# {'missing_key': [2]}

dict setdefault() allow to assign values to missing keys on the fly. But in defaultdict, default value is specified up front when you initialize the container.

Example

In the below example, int is passed as the datatype to the defaultdict. Hence, any key that does not already exist in d will be assigned a value of 0.

from collections import defaultdict

d = defaultdict(int)
print(d[3])

# Output
# 0

If list is passed to constructor of defaultdict, it results in the creation of a dictionary of lists. So a key with no value is now assigned an empty list upon entry. Moreover, all values are now stored in a list format. To add value to the defaultdict, use the append function of list.

from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

# Create dict with list as default factory
d = defaultdict(list)

for k, v in s:
    d[k].append(v)

print(sorted(d.items()))

# Output
# [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

In the above example, if key is not present in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up return the list for that key; and the list.append() operation adds another value to the list. It is simpler and faster than an equivalent technique using dict.setdefault().