从文本文件填充字典

Populating a dictionary from text file

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

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()

我在第 1 行收到错误 "too many variables to unpack"。有什么建议吗?谢谢!

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

其次,您拆分了一个空字符串。应该是 .split(',') 以逗号分割。

最后,我会考虑使用 csv class 来读取 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