mada74
mada74

Reputation: 1

Parsing CSV data into a dict

I'm currently trying to pass csv data into an empty dict. Column A of the dict has the book title, column B the book's author. So once passed in, I'm hoping my dict will look like this:

books = {'Booktitle1':'Author1','Booktitle2':'Author2','Booktitle 3':'Author3'}

Upvotes: 0

Views: 73

Answers (1)

Regzand
Regzand

Reputation: 21

Something like this should solve your problem:

import csv

with open('books.csv') as file:
    reader = csv.reader(file)
    books = dict(line for line in reader if line)

The file like this:

Booktitle1,Author1
Booktitle2,Author2
Booktitle3,Author3

Will give you:

books = {'Booktitle1': 'Author1', 'Booktitle2': 'Author2', 'Booktitle3': 'Author3'}

The if line takes care of empty lines

If your file has a header, you can take a look here

Upvotes: 2

Related Questions