我有一個將CSV文件分割成3個值的函數(shù);isbn,author并且title然后創(chuàng)建映射的字典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)問題是,目前我可以為每個字典創(chuàng)建一個字典,isbn但不能為所有字典創(chuàng)建字典。我當前的輸出是:{'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條經(jīng)驗 獲得超6個贊
您需要isbn_dict在循環(huán)之前聲明,如下所示:
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)
這樣,每個項目都將添加到現(xiàn)有字典中。
添加回答
舉報
0/150
提交
取消