import csv
def csv_to_kvs(fileName):
stringFloats = []
with open(fileName,'r') as csvFile:
csvreader = csv.reader(csvFile)
for row in csvreader:
stringFloats.append(row)
print(stringFloats)
I am trying to take a CSV file that is in string,float,float,float format of 10 rows and I have to make the string become a key-value pair with all the floats on the corresponding row.
So if the CSV file is:
age,16,17,18
area,1,7,4
call,2,3,6
The code needs to return {age:[16,17,18],etc...}. Any steps in the right direction are appreciated. I am learning CSV file reading and don't understand it too well.
When you read the row, you have the dictionary key in column 0 and the values in the remaining columns. You can slice the row, optionally converting to float on the way, and assign to the needed dict.
import csv
def csv_to_kvs(fileName):
stringFloats = {}
with open(fileName,'r') as csvFile:
csvreader = csv.reader(csvFile)
for row in csvreader:
# assuming 1 and following should be floats
stringFloats[row[0]] = [float(val) for val in row[1:]]
print(stringFloats)
return stringFloats
(...and come to terms with 4 space indentation!)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.