2017-03-03 55 views
0

我正在嘗試獲取所有單詞及其標記並將其計入字典中。但是,我不斷收到一個KeyError,我不明白爲什麼。重要錯誤Python

sent = [[('Merger', 'NOUN'), ('proposed', 'VERB')], [('Wards', 'NOUN'), ('protected', 'VERB')]] 

dicts = {} 

for x in sent: 
    for y in x: 
     if y[0] in dicts.keys(): 
      dicts[y[0]][y[1]] = 1 
     else: 
      dicts[y[0]][y[1]] += 1 

錯誤:

KeyError    Traceback (most recent call last) 
    <ipython-input-19-17c6695bd911> in <module>() 
    17    dicts[y[0]][y[1]] = 1 
    18   else: 
---> 19    dicts[y[0]][y[1]] += 1 

    KeyError: 'Merger' 
+0

你從高聲望的人兩次快速的答案,但我努力理解的'類型的字典用處[Y [0] ] [y [1]] + = 1'。你期待什麼輸出? – roganjosh

+0

@roganjosh嗨,我想創建一個嵌套的字典。所以它會是{Merger:{Noun:1}} –

+0

我認爲它實際上解決了TerryA的編輯答案。它只是看起來不正確,我想知道是否有迂迴的事情發生。 – roganjosh

回答

1

你有你的條件語句以錯誤的方式。你想檢查密鑰是否存在於字典中 - 如果沒有,那麼你創建密鑰。那麼,你嵌套得太過分了。你只需要dicts[y[0]]

有一個簡單的解決方法:在in dicts.keys()之前加not,但是然後擺脫[y[1]]

在全:

for x in sent: 
    for y in x: 
     if y[0] not in dicts.keys(): 
      dicts[y[0]] = 1 
     else: 
      dicts[y[0]] += 1 
2

你也應該考慮尋找collections.defaultdictcollections.Counter

一個defaultdict將在缺省值自動填充,一個Counterdict專門爲計數:

from collections import defaultdict 
from collections import Counter 

sent = [[('Merger', 'NOUN'), ('proposed', 'VERB')], [('Wards', 'NOUN'), ('protected', 'VERB')]] 

dicts = defaultdict(Counter) # A default dictionary of Counters 
for x in sent: 
    for y in x: 
     dicts[y[0]][y[1]] += 1 

print(dicts) 
# defaultdict(<class 'collections.Counter'>, {'Merger': Counter({'NOUN': 1}), 'proposed': Counter({'VERB': 1}), 'Wards': Counter({'NOUN': 1}), 'protected': Counter({'VERB': 1})}) 

如果您想跳過Counter ,你可以只使用一個返回defaultdict(int)和不帶參數的輔助功能:

from collections import defaultdict 

def int_dict(): 
    return defaultdict(int) 

dicts = defaultdict(int_dict) 
for x in sent: 
    for y in x: 
     dicts[y[0]][y[1]] += 1 

print(dicts) 
# defaultdict(<function a at 0x112c48048>, {'Merger': defaultdict(<class 'int'>, {'NOUN': 1}), 'proposed': defaultdict(<class 'int'>, {'VERB': 1}), 'Wards': defaultdict(<class 'int'>, {'NOUN': 1}), 'protected': defaultdict(<class 'int'>, {'VERB': 1})}) 
+0

幾乎我要發佈的內容,所以我不會重複。你可以通過在'for in'中解壓它來避免元組上的醜陋的索引訪問。例如'用於名稱,類型爲x:' –