如何用我的代码将多个包含元组的列表转换为字典


taggedwords=[]
for sentence in range(0,len(wordlist)):
tagged = tagger.tag(wordlist[sentence])
print(tagged)

输出是元组的多个列表。我能转换所有它们的唯一方法是进行

dict(tagger.tag(wordlist[sentence]))

然而,这只会将一个列表转换为字典。有没有办法同时完成所有104项任务?

如果你想要一个大字典,你可以做到:

bigdict = {}
for sentence in range(0,len(wordlist)):
tagged = tagger.tag(wordlist[sentence])
bigdict = {**bigdict, **dict(tagged)}

如果你想要一个每个元素都是字典的列表,那么

dicts = []
for sentence in range(0,len(wordlist)):
tagged = tagger.tag(wordlist[sentence])
dicts.append(dict(tagged))

您可以简单地使用字典的update方法。它获取一系列元组,并有效地将它们添加到字典中。像这样:

all_tagged = {}
for sentence in wordlist:
tagged = tagger.tag(sentence)
all_tagged.update(tagged)

注1:我还简化了for循环。不需要对范围进行迭代,然后对wordlist进行索引。您可以简单地迭代wordlist的元素!:(

注意2:这个解决方案比Joe的略快,因为它更新了字典,而不是覆盖现有的字典。


还有:sentence_list不是比wordlist更好的名字吗?

最新更新