I am trying to take input from a CSV file and then push it into a dictionary format (I am using Python 3.x).
I use the code below to read in the CSV file and that works:
import csv
reader = csv.reader(open('C:\\Users\\Chris\\Desktop\\test.csv'), delimiter=',', quotechar='|')
for row in reader:
print(', '.join(row))
But now I want to place the results into a dictionary. I would like the first row of the CSV file to be used as the "key" field for the dictionary with the subsequent rows in the CSV file filling out the data portion.
Sample data:
Date First Name Last Name Score
12/28/2012 15:15 John Smith 20
12/29/2012 15:15 Alex Jones 38
12/30/2012 15:15 Michael Carpenter 25
How can I get the dictionary to work?
Create a dictionary, then iterate over the result and stuff the rows in the dictionary. Note that if you encounter a row with a duplicate date, you will have to decide what to do (raise an exception, replace the previous row, discard the later row, etc…)
Here’s test.csv:
and the corresponding program:
yields:
or, with DictReader:
results in:
Or perhaps you want to map the column headings to a list of values for that column:
That yields: