'collections.defaultdict' 对象没有属性 'append'

Fre*_*ear 5 python dictionary

我在尝试使用的代码片段中遇到了问题。这是代码:

from collections import defaultdict
from string import ascii_lowercase
words = defaultdict(list)
with open('/usr/share/dict/words') as fin:
    for word in fin:
        if len(word) == 5: 
             words.append(word)
Run Code Online (Sandbox Code Playgroud)

每当我尝试运行代码时,它都会返回错误:

AttributeError: type object 'collections.defaultdict' has no attribute 'append'
Run Code Online (Sandbox Code Playgroud)

有什么建议?

小智 4

collections.defaultdict是一种字典;它没有append方法。这仅适用于该list类型。

查看您的代码,您实际上没有理由使用类似字典的结构。您的目标是收集单个项目,而不是键/值对。 words应该只是一个列表:

words = []
with open('/usr/share/dict/words') as fin:
    for word in fin:
        if len(word) == 5: 
            words.append(word)
Run Code Online (Sandbox Code Playgroud)

另外,您可能希望str.rstrip()在每一行上调用以删除尾随的换行符:

for word in fin:
    word = word.rstrip()
Run Code Online (Sandbox Code Playgroud)