密钥错误Python

2024-10-05 14:28:41 发布

您现在位置: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

错误:

^{pr2}$

Tags: in标记for字典错误单词mergersent
2条回答

你把条件句弄错了。您需要先检查字典中是否存在该键,如果不存在,则创建该键。那么,你的巢穴太深了。您只需要dicts[y[0]]

有一个简单的修复方法:在in dicts.keys()之前添加not,然后去掉{}。在

全部:

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

您还应该考虑查看^{}和{a2}:

一个defaultdict将自动填充一个默认值,Counter是一个专门用于计数的dict

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,只需使用一个helper函数,该函数返回一个defaultdict(int),并且不带任何参数:

^{pr2}$

相关问题 更多 >