Chapter 7: More file handling

Reading CSV files into a dict

face Josiah Wang

If you have tried the previous exercise, you might have found yourself counting which columns the final marks and grade are in.

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)

Exercise

Update your code from the previous exercise. Read in the required columns into a dict rather than a list. Hopefully that makes life a bit easier! Remember to NOT explicitly read in the first line - this will be done automatically by csv.DictWriter!