可能的重复:
如何制作一个 python 字典,返回字典中缺少的键的键,而不是引发 KeyError? https://stackoverflow.com/questions/6229073/how-to-make-a-python-dictionary-that-returns-key-for-keys-missing-from-the-dicti
我需要类似的东西defaultdict
。但是,对于字典中没有的任何键,它应该返回键本身。
最好的方法是什么?
使用魔法__missing__
method:
>>> class KeyDict(dict):
... def __missing__(self, key):
... return key
...
>>> x = KeyDict()
>>> x[2]
2
>>> x[2]=0
>>> x[2]
0
>>>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)