Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 987
sam Avatar asked Oct 06 '13 16:10

sam


1 Answers

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
like image 69
Ashwini Chaudhary Avatar answered Oct 24 '22 20:10

Ashwini Chaudhary