2013-03-28 136 views
2

重點對象我創建了一個類,讓我來存儲元數據與任意詞典按鍵,仍然與原來的對象類型通過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 

回答

2

存儲「元」的數據的更傳統的方式用一個字典沿着將任一:

  1. 維持兩個dict s的相同的密鑰集合,一個用於實際的數據,一個用於「元」
  2. dict用(「原始」)鍵,和值是2元組:(價值,項目的元數據)

兩者都是簡單的,不需要特殊的魔力。您還可以避免像您在問題中描述的問題(以及其他問題)。

+0

我試圖避免使用雙字典解決方案,因爲不必使用該空間就很好(我們應用程序中的字典可能會變得非常大)。但是,看起來這將是一條路。謝謝! – Hersheezy

+0

@Hersheezy如果你覺得這個答案有幫助,可以隨時接受它;) – shx2

0

我做了少許修改你的基本代碼:

def __repr__(self): 
    return 'DictKey(' + self.member + ')' 

然後,如果你想檢索DictKey的實例中密鑰的集合,你可以做到以下幾點:

index_of_instance = d.keys().index('hello') 
my_instance_of_dict_key = d.keys()[index_of_instance] 

希望能幫助到你。

+0

這兩個調用keys()都是O(n)我相信。我需要查找是恆定的時間。雖然謝謝! – Hersheezy