Python 身份字典
我需要一个类似于 defaultdict
的东西。不过,对于字典中不存在的任何键,它应该返回这个键本身。
有什么好的方法可以做到这一点呢?
3 个回答
2
class Dict(dict):
def __getitem__(self, key):
try:
return super(Dict, self).__getitem__(key)
except KeyError:
return key
>>> a = Dict()
>>> a[1]
1
>>> a[1] = 'foo'
>>> a[1]
foo
如果你需要支持 Python 版本低于 2.5 的话,这个方法是有效的。因为在 2.5 版本中,增加了 @katrielalex 提到的 __missing__
方法。
10
你是说像下面这样吗?
value = dictionary.get(key, key)
15
使用神奇的 __missing__
方法:
>>> class KeyDict(dict):
... def __missing__(self, key):
... return key
...
>>> x = KeyDict()
>>> x[2]
2
>>> x[2]=0
>>> x[2]
0
>>>