关键错误Python

时间:2017-03-03 00:20:21

标签: python python-3.x

我试图获取所有单词及其标签并计入字典。但是,我一直得到一个KeyError,我不明白为什么。

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'

2 个答案:

答案 0 :(得分: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})})

答案 1 :(得分:1)

你的条件错误了。您想先检查字典中是否存在密钥 - 如果不存在,则创建密钥。然后,你已经嵌套了太多。您只需要AlarmManager

有一个简单的解决方法:在dicts[y[0]]之前添加not,然后摆脱in dicts.keys()

完整:

[y[1]]