Search code examples
pythoncollectionsdefaultdict

Change default return value of a defaultdict *after* initialization


Is there a way to change the default_factory of a defaultdict (the value which is returned when a non-existent key is called) after it has been created?

For example, when a defaultdict such as

d = defaultdict(lambda:1)

is created, d would return 1 whenever a non-existent key such as d['absent'] is called. How can this default value been changed to another value (e.g., 2) after this initial definition?


Solution

  • Assign the new value to the default_factory attribute of defaultdict.

    default_factory:

    This attribute is used by the __missing__() method; it is initialized from the first argument to the constructor, if present, or to None, if absent.

    Demo:

    >>> dic = defaultdict(lambda:1)
    >>> dic[5]
    1
    >>> dic.default_factory = lambda:2
    >>> dic[100]
    2