0

I have a function that takes a CSV file and splits it into 3 values; isbn, author and title then creates a dictionary that maps isbn values to tuples containing the author and title. This is my current code:

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)

The problem is that at the moment I can get it to create a dictionary for each isbn but not one for all of them. My current output is:

{'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')}

What my output should be:

{'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')}

It's probably a really simple issue but I cannot get my head around it.

4

2 回答 2

8

使用该csv模块可以更轻松、更高效地处理,以及 dict 理解:

import csv

def isbn_dictionary(filename):
    with open(filename, newline='') as infile:
        reader = csv.reader(infile)
        return {isbn: (author, title) for isbn, author, title in reader}

您的代码仅每行创建一个字典,并且仅打印该字典。您可能想返回字典。

使用 dict 理解不仅使函数更紧凑,而且效率更高。字典是在 C 代码中一次性创建的,而不是在 Python 循环中一一添加键和值。

于 2013-05-16T08:52:09.083 回答
3

您需要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)

这样,每个项目都会添加到现有字典中。

于 2013-05-16T08:51:23.523 回答