可能重複:
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?蟒蛇身份詞典
我需要的東西就像一個defaultdict
。但是,對於不在字典中的任何密鑰,它應該返回密鑰本身。
這樣做的最好方法是什麼?
可能重複:
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?蟒蛇身份詞典
我需要的東西就像一個defaultdict
。但是,對於不在字典中的任何密鑰,它應該返回密鑰本身。
這樣做的最好方法是什麼?
使用魔法__missing__
方法:
>>> class KeyDict(dict):
... def __missing__(self, key):
... return key
...
>>> x = KeyDict()
>>> x[2]
2
>>> x[2]=0
>>> x[2]
0
>>>
你是指以下類似的東西?
value = dictionary.get(key, key)
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__
方法)。
術語nitpick:身份dict通常被認爲是一個字典,它使用對象身份(`id`)作爲鍵而不是散列。 – delnan 2011-12-13 20:13:50
啊,我沒有找到其他問題。感謝您指出。有沒有辦法來鞏固這兩個問題?然而,對另一個問題的接受答案卻被證明是錯誤的,並且OP沒有費心改變他的接受程度。 – max 2011-12-14 00:54:50
@max:有一個堆棧溢出過程來處理重複的問題。它將全部得到照顧=) – katrielalex 2011-12-14 01:53:27