从CSV数据创建字典 [英] Creating a dictionary from CSV data
问题描述
我有一个将CSV文件分割成3个值的函数;然后isbn
,author
和title
创建一个字典,该字典将isbn
值映射到包含author
和title
的元组.这是我当前的代码:
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屋!