2011-12-13 54 views
4

可能重复:
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?蟒蛇身份词典

我需要的东西就像一个defaultdict。但是,对于不在字典中的任何密钥,它应该返回密钥本身。

这样做的最好方法是什么?

+2

术语nitpick:身份dict通常被认为是一个字典,它使用对象身份(`id`)作为键而不是散列。 – delnan 2011-12-13 20:13:50

+0

啊,我没有找到其他问题。感谢您指出。有没有办法来巩固这两个问题?然而,对另一个问题的接受答案却被证明是错误的,并且OP没有费心改变他的接受程度。 – max 2011-12-14 00:54:50

+0

@max:有一个堆栈溢出过程来处理重复的问题。它将全部得到照顾=) – katrielalex 2011-12-14 01:53:27

回答

11

使用魔法__missing__方法:

>>> class KeyDict(dict): 
...  def __missing__(self, key): 
...    return key 
... 
>>> x = KeyDict() 
>>> x[2] 
2 
>>> x[2]=0 
>>> x[2] 
0 
>>> 
8

你是指以下类似的东西?

value = dictionary.get(key, key) 
1
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(其中新增由@katrielalex提到__missing__方法)。