如何重写python dicts以获取默认值

web*_*uth 3 python dictionary

我想重写Python的字典访问机制" getitem ",以便能够返回默认值.

我正在寻找的功能就像

a = dict()
a.setdefault_value(None)
print a[100] #this would return none
Run Code Online (Sandbox Code Playgroud)

任何提示?

谢谢

Joc*_*zel 11

已有collections.defaultdict:

from collections import defaultdict

a = defaultdict(lambda:None)
print a[100]
Run Code Online (Sandbox Code Playgroud)