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 titl
Solution 1:
Use the csv
module for easier and more efficient processing, and a dict comprehension:
import csv
defisbn_dictionary(filename):
withopen(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.
Solution 2:
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.
Post a Comment for "Creating A Dictionary From Csv Data"