Reputation: 97
So I'm writing in data from a CSV file into Python so I can do some math with it. The data in the CSV file is mock student grades; so a student's name, and then 5 test scores. I'm using the following code to put all the data into a dictionary:
csvfile = open('Lab03-testdata.csv', newline='')
linesreader = csv.reader(csvfile, delimiter=';')
testScores = {}
for l in linesreader:
testScores[l[0]] = l[1:]
This works, but each key has a corresponding list of strings not ints. My output looks something like:
'John Doe': ['100', '55', '34', '22', '99']
In order to do any math, I've been having to use a for loop to add the test scores I want into separate lists, and convert the scores into ints as I do that. However I want all the data in the dictionary to already be ints. I'm wanting something more like this:
'John Doe': [100, 55, 34, 22, 99]
So how can I convert the list of values into integers?
Upvotes: 0
Views: 59
Reputation: 17322
you have to convert from str to int your data
for l in linesreader:
testScores[l[0]] = list(map(int, l[1:]))
Upvotes: 0
Reputation: 114025
Add an int(...)
cast to this code:
for l in linesreader:
testScores[l[0]] = l[1:]
Notice the change within the for loop:
for l in linesreader:
testScores[l[0]] = [int(i) for i in l[1:]]
Upvotes: 1