0

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'}
2
  • 1
    Does this answer your question? Best way to convert csv data to dict Commented Jan 27, 2021 at 20:48
  • for book, author in csv.reader(csvfile): books[book] = author ? Commented Jan 27, 2021 at 20:49

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.