Lesson 10
I am Your Father
Chapter 7: More file handling
Reading CSV files into a dict
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 |
|
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 |
|
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
!