重點對象我創建了一個類,讓我來存儲元數據與任意詞典按鍵,仍然與原來的對象類型通過in
測試:蟒蛇檢索字典
class DictKey:
def __init__(self, key):
self.hashkey = hash(key)
self.member = key
def __hash__(self):
return self.hashkey
def __repr__(self):
return 'DictKey(' + self.strkey + ')'
def __cmp__(self, o):
return cmp(self.member, o)
d = {}
key = DictKey('hello')
d[key] = 'world'
print key.hashkey
print hash('hello')
print key in d
print 'hello' in d
print DictKey('hello') in d
產生輸出:
840651671246116861
840651671246116861
True
True
True
現在,給出的字符串「你好」,我需要一個從所述串是在固定時間內創建DictKey實例:
if 'hello' in d:
#need some way to return the instance of DictKey so I can get at it's member
tmp = d.getkey('hello')
tmp.member
我試圖避免使用雙字典解決方案,因爲不必使用該空間就很好(我們應用程序中的字典可能會變得非常大)。但是,看起來這將是一條路。謝謝! – Hersheezy
@Hersheezy如果你覺得這個答案有幫助,可以隨時接受它;) – shx2