简体   繁体   中英

Read from file to dictionary as floats instead of strings

I'm loading and extracting data from python, which I want to be stored in a dictionary.

I'm using csv to write read the data and externally it is just stored as to comma-separated columns. This works great, but when the data is initially read it (obviously) is read as string. I can convert it to a dictionary with both keys and values as floats using two lines of code, but my question whether I can load the data directly as floats into a dictionary.

My original code was:

reader = csv.reader(open('testdict.csv','rb'))
dict_read = dict((x,y) for (x,y) in reader)

Which I have changed to:

reader = csv.reader(open('testdict.csv','rb'))
read = [(float(x),float(y)) for (x,y) in reader]
dict_read = dict(read)

which loads the data in the desired way.

So, is it possible to modify the first dict_read = dict((x,y) for (x,y) in reader) to do what the code below does?

SOLUTION: The solution is to use the map-function, which has to be used on iterable objects:

dict_read = dict(map(float,x) for x in reader)

尝试这个:

dict_read = dict((map(float,x) for x in reader)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM