sam
sam

Reputation: 1436

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?

Upvotes: 12

Views: 2914

Answers (2)

田雪津
田雪津

Reputation: 21

Please be careful with defaultdict.default_factory, the behaviur could be unexpected.

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

This is because when require dic[5], the missed key is added to the dict with current default value. And modify dic.default_factory afterward will not change the value of 5.

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

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

Upvotes: 16

Related Questions