从CSV数据创建字典

jev*_*ans 0 python dictionary python-3.x

我有一个函数,它接受一个CSV文件,并将其分为3个值; isbn,author并且title然后创建映射的字典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)
Run Code Online (Sandbox Code Playgroud)

问题是,目前我可以让它为每个人创建一个字典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')}
Run Code Online (Sandbox Code Playgroud)

我的输出应该是什么:

{'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')}
Run Code Online (Sandbox Code Playgroud)

这可能是一个非常简单的问题,但我无法理解它.

Mar*_*ers 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}
Run Code Online (Sandbox Code Playgroud)

您的代码每行只创建一个字典,只打印字典.您可能想要返回字典.

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