Change the value of the return value to defaultdict * after * initialization

Is there a way to change default_factory to the defaultdict value (the value that is returned when a nonexistent key is called) after it has been created?

For example, when the defaultdict parameter, for example

d = defaultdict(lambda:1) 

d will return 1 whenever a nonexistent key is called, for example d['absent'] . How was this default value changed to another value (e.g. 2) after this initial definition?

+6
source share
1 answer

Assign a new value to the default_factory defaultdict attribute.

default_factory :

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

Demo:

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

Source: https://habr.com/ru/post/955351/


All Articles