Chapter 10: Files

Reading CSV files into a dict

face Josiah Wang

It might be a hassle to count the index of columns you want from a CSV, especially when there are too many columns!

To make life easier, you can also read in the CSV files into a dict, using a csv.DictReader object. You can then access elements using the column names as keys (from the first row). There is also no need to explicitly read the header row (this is automatically done by csv.DictReader).

1
2
3
4
5
6
7
8
import csv

with open("students.csv") as csv_file: 
    reader = csv.DictReader(csv_file)

    for row in reader: 
        print(f"Student {row['name']} is from the Faculty of {row['faculty']}, "
              f"{row['department']} dept.")

If the CSV file does not contain a header row, you will need to specify your own keys. You can do this by assigning the fieldnames argument with a list that contains your column names.

1
2
headers = ["name", "faculty", "department"] 
reader = csv.DictReader(csv_file, fieldnames=headers)