2017-03-03 53 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:' –