从文本文件填充字典

1 python dictionary file-handling

我正在尝试从一个文本文件中填充一个字典,该文件有两列作者和标题,用逗号分隔。我的代码在下面

f = open('books.txt', 'r')          
books = {}
for l in f:
    author,title = l.strip().split()
    if author in books:
        books[author].append(title)
    else:
        books[author]=[title]
f.close()
Run Code Online (Sandbox Code Playgroud)

我在第 1 行收到错误“要解压的变量太多”。有什么建议吗?谢谢!

Jef*_*eff 5

有几件事,您可能应该使用with open在 python 中读取文件的方式(请参阅文档)。它会在块的末尾自动关闭。

其次,你拆分一个空字符串。应该是.split(',')用逗号分隔。

最后,我会考虑使用csv 类来读取 csv 文件。如果书名或作者中有逗号,这尤其有用。

您的代码的工作示例:

with open('books.txt', 'r') as book_file:
    books = {}
    for l in book_file:  
        author,title = l.strip().split(',')
        if author in books:
            books[author].append(title)
        else:
            books[author]=[title]

print books
Run Code Online (Sandbox Code Playgroud)