简体   繁体   中英

Creating a dictionary from CSV data

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.

Use the csv module for easier and more efficient processing, and a dict comprehension:

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}

Your code only created a dictionary per line and only printed the dictionary. You probably wanted to return the dictionary instead.

Using a dict comprehension not only makes the function more compact, it is also more efficient. The dictionary is created in one go, in C code, instead of in a Python loop adding keys and values one by one.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM