2014-02-05 24 views
1

我試圖在搜索鍵的字典列表時找到鍵。但字符串與字典鍵不完全匹配。這是我到目前爲止:在詞典鍵中查找字符串,其中的字符串並非完全是字典中的鍵

if string in d.keys(): 
    print 'found' 

我想找到鑰匙。

+0

什麼樣的匹配的是我們真的在看什麼?字符串是任何鍵或子序列的子字符串嗎?甚至是一個字謎? 順便說一句壞的問題。 – tMJ

+0

說key ='abc123',我用來搜索的字符串是'bc1' – WongSifu

回答

5

我不認爲有任何東西比橫跨密鑰的線性掃描更好。

print [k for k in d if string in k] 
0

假設distance比較兩個字符串並返回一個較低的數字,如果字符串是一個很好的匹配和較高的號碼時的字符串是一個糟糕的比賽。 (你必須決定在那裏僱用什麼,Levenshtein等)。

bestMatch = None 
value = None 
for k, v in d.items(): 
    match = distance (k, searchedKey) 
    if bestMatch == None or bestMatch > match: 
     bestMatch = match 
     value = v 
print (value) # the value of the best matched key 
0

如果我正確理解你的問題,你想模糊字符串與鍵的匹配。這裏是我的建議:

>>> keys = ["apple", "plum", "pear", "carrot"] 
>>> d = {key:val for key, val in zip(keys,range(4))} 
>>> d 
{'plum': 1, 'carrot': 3, 'pear': 2, 'apple': 0} 
>>> 
>>> searchKey = "aple" 
>>> 
>>> import difflib 
>>> 
>>> try: 
...  searchVal = d[searchKey] 
... except: 
...  closeKey = difflib.get_close_matches(searchKey, d.keys(), 1)[0] 
...  searchVal = d[closeKey] 
... 
>>> searchVal 
0 
1

如果這是你的東西的程序依賴於很多,你可以這樣做:

class ApproxDict(dict): 

     def __contains__(self, item): 
      # item contains the key. Do what you need with it. 
      return True # or False again this depends on what you want 

無論使用其他解決方案的建議執行__contains__()方法。 這樣你就可以自定義查找並保留python的可讀性。

對於您在您的評論一種高精度鑰匙串查找:

>>> class ApproxDict(dict): 
    ...  def __contains__(self, item): 
    ...   for key in self.keys(): 
    ...    if item in key: 
    ...     return True 
    ...   return False 
    ... 
    >>> d = ApproxDict() 
    >>> d['abc123'] = "some value" 
    >>> 'bc1' in d 
    True 
    >>> 'bc2' in d 
    False 
    >>> 

the python data model documentation. 希望有所幫助。

順便說一句,用dictionnary:

if key in d: 
     # whatever 

等同於:

if key in d.keys(): 
     # whatever 
相關問題