python - Change default return value of a defaultdict *after* initialization -
is there way change default_factory of defaultdict (the value returned when non-existent key called) after has been created?
for example, when defaultdict such as
d = defaultdict(lambda:1) is created, d return 1 whenever non-existent key such d['absent'] called. how can default value been changed value (e.g., 2) after initial definition?
assign new value default_factory attribute of defaultdict.
this attribute used
__missing__()method; initialized first argument constructor, if present, ornone, if absent.
demo:
>>> dic = defaultdict(lambda:1) >>> dic[5] 1 >>> dic.default_factory = lambda:2 >>> dic[100] 2
Comments
Post a Comment