我有一个将CSV文件分割成3个值的函数;isbn,author并且title然后创建映射的字典isbn值到包含元组author和title。这是我当前的代码:def isbn_dictionary(filename): file = open(filename, 'r') for line in file: data = line.strip('\n') author, title, isbn = data.split(',') isbn_dict = {isbn:(author, title)} print(isbn_dict)问题是,目前我可以为每个字典创建一个字典,isbn但不能为所有字典创建字典。我当前的输出是:{'0-586-08997-7': ('Kurt Vonnegut', 'Breakfast of Champions')}{'978-0-14-302089-9': ('Lloyd Jones', 'Mister Pip')}{'1-877270-02-4': ('Joe Bennett', 'So Help me Dog')}{'0-812-55075-7': ('Orson Scott Card', 'Speaker for the Dead')}我的输出应该是:{'0-586-08997-7': ('Kurt Vonnegut', 'Breakfast of Champions'),'978-0-14-302089-9': ('Lloyd Jones', 'Mister Pip'),'1-877270-02-4': ('Joe Bennett', 'So Help me Dog'),'0-812-55075-7': ('Orson Scott Card', 'Speaker for the Dead')}这可能是一个非常简单的问题,但我无法解决。
2 回答

红糖糍粑
TA贡献1815条经验 获得超6个赞
您需要isbn_dict在循环之前声明,如下所示:
def isbn_dictionary(filename):
file = open(filename, 'r')
isbn_dict = {}
for line in file:
data = line.strip('\n')
author, title, isbn = data.split(',')
isbn_dict[isbn] = (author, title)
print(isbn_dict)
这样,每个项目都将添加到现有字典中。
添加回答
举报
0/150
提交
取消