python身份字典

max*_*max 6 python dictionary python-3.x

可能重复:
如何制作一个python字典,返回字典中缺少键的键,而不是引发KeyError?

我需要类似的东西defaultdict.但是,对于任何不在字典中的键,它应该返回键本身.

最好的方法是什么?

Kat*_*iel 13

使用魔法__missing__:

>>> class KeyDict(dict):
...     def __missing__(self, key):
...             return key
... 
>>> x = KeyDict()
>>> x[2]
2
>>> x[2]=0
>>> x[2]
0
>>> 
Run Code Online (Sandbox Code Playgroud)


moo*_*eep 8

你是说像下面这样的东西?

value = dictionary.get(key, key)
Run Code Online (Sandbox Code Playgroud)