2014-11-24 36 views
0

我有以下代碼:如何處理在Python字典找不到鑰匙

from math import sqrt 
from collections import Counter 

def forSearch(): 
    words = {'bit':{1:3,2:4,3:19,4:0},'shoe':{1:0,2:0,3:0,4:0},'dog':{1:3,2:0,3:4,4:5}, 'red':{1:0,2:0,3:15,4:0}} 
    search = {'bit':1,'dog':3,'shoe':5} 
num_files = 4 

    file_relevancy = Counter() 
    c = sqrt(sum([x**2 for x in search.values()])) 
    for i in range(1, num_files+1): 
     words_ith_val = [words[x][i] for x in search.keys() ] 
     a = sum([search[key] * words[key][i] for key in search.keys()]) 
     b = sqrt(sum([x**2 for x in words_ith_val])) 
     file_relevancy[i] = (a/(b * c)) 

    return [x[0] for x in file_relevancy.most_common(num_files)] 

print forSearch() 

然而,這其中包含在搜索,但無法用語言文字方面的問題:

我想在這裏這樣說:

for i in range(1, num_files+1): 
    if corresponding key in words cannot be found 
     insert it and make its value = 0 
    words_ith_val = [words[x][i] for x in search.keys() ] 

那麼它應該工作?

除非其他人有更好的建議嗎?

+0

您的'words'變量聲明應該能夠使用數組語法:'words = {'bit':[3,4,19,0]'shoe':[0,0,0,0], '狗':[3,0,4]}。你可能想堅持0-索引(從0開始計數,而不是1) – 2014-11-24 08:12:02

+0

我不允許改變單詞的方式。 – DannyBoy 2014-11-24 08:36:56

回答

2

collections.defaultdict

import collections 

D = collections.defaultdict(int) 
D['foo'] = 42 
print D['foo'], D['bar'] 
+0

你能解釋一下嗎? – 2014-11-24 08:18:50

+0

@VincentBeltman:該示例的哪個部分令人困惑? – 2014-11-24 08:20:30

+0

沒關係沒看到鏈接。 – 2014-11-24 08:20:54

0

這個怎麼樣代碼:

if key not in words: 
    words[key] = {k+1: 0 for k in range(num_files)} 

在你的代碼,你可以嘗試做

for key in search.keys(): 
    if key not in words: 
     words[key] = {k+1: 0 for k in range(num_files)} 
    words_ith_val = [words[key][k + 1] for k in range(num_files)] 
+0

這是一個簡化的問題,實際上有數百個文件。 – DannyBoy 2014-11-24 08:33:11

+0

@DannyBoy,現在答案在num_files變量上進行參數化。 – 2014-11-24 09:02:04

+0

我得到一個錯誤:UnboundLocalError:在賦值之前引用的局部變量'key' – DannyBoy 2014-11-24 09:08:03

2

可以使用defaultdict:

from collections import defaultdict 
d = defaultdict(int) 

這將初始化密鑰是在訪問和默認值創建的字典爲0,可以使用其他類型還有:

defaultdict(dict) 
defaultdict(list) 

他們將一個空的字典/列表進行初始化。 您也可以使用工廠方法覆蓋默認值。詳情請參閱https://docs.python.org/2/library/collections.html#collections.defaultdict

+0

這個問題被簡化了,我必須使用字典中的單詞,並且以這種格式。 – DannyBoy 2014-11-24 08:36:29

相關問題