Home > Mobile >  multiple lists from csv dictreader
multiple lists from csv dictreader

Time:12-29

I have a simple CSV file with two keys, "Title" and "Author" with a bunch of data.

I want to make a list of the titles, and then a list of the authors. My code is as below. It prints the title_list but no the author_list, why?

import csv

with open("books.csv", encoding="utf-8-sig") as books_csv:
    books_reader = csv.DictReader(books_csv)
    title_list = [book["Title"] for book in books_reader]
    author_list = [book["Author"] for book in books_reader]

    print(title_list)
    print(author_list)```

CodePudding user response:

books_reader is an iterator. When you use list-comprehension to define title_list you exhaust the iterator leaving books_reader empty. That is why when you go to define author_list it returns nothing. Using list-comprehension for this problem is not the correct solution. You are probably looking for the following:

import csv

title_list = []
author_list = []
with open("books.csv", encoding="utf-8-sig") as books_csv:
    books_reader = csv.DictReader(books_csv)
    for book in books_reader:
        title_list.append(book["Title"])
        author_list.append(book["Author"])
  • Related