从CSV数据创建字典

时间:2013-05-16 08:49:35

标签: python dictionary python-3.x

我有一个函数,它接受一个CSV文件并将其分成3个值; isbnauthortitle会创建一个字典,将isbn值映射到包含authortitle的元组。这是我目前的代码:

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 个答案:

答案 0 :(得分:8)

使用csv module更简单,更有效的处理和词典理解:

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}

您的代码仅在每行创建字典 并且只打印字典。您可能希望返回字典。

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

答案 1 :(得分: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)

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