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?
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 toNone
, if absent.
Demo:
>>> dic = defaultdict(lambda:1)
>>> dic[5]
1
>>> dic.default_factory = lambda:2
>>> dic[100]
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With