从CSV数据创建字典 [英] Creating a dictionary from CSV data

查看:66
本文介绍了从CSV数据创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将CSV文件分割成3个值的函数;然后isbnauthortitle创建一个字典,该字典将isbn值映射到包含authortitle的元组.这是我当前的代码:

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)

问题是,目前我可以为每个isbn创建一个字典,但不能为所有所有字典创建一个字典.我当前的输出是:

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

我的输出应该是:

{'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.

推荐答案

您需要在循环之前声明isbn_dict,如下所示:

You need to declare isbn_dict before the loop, like this:

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)

通过这种方式,每个项目都将添加到现有字典中.

This way, each item is added to the existing dictionary.

这篇关于从CSV数据创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆