I am using the csv python package to read a csv file like this:
r = csv.DictReader(open(r'd:\aaa.csv', 'rb'))
for row in r:
print row
The problem is that all the values in the resulting dictionary are strings and I need them to be converted to the respective types. I have a mapping between column names and the types.
Are there any shortcuts here or do I have to do it all myself?
EDIT
I have marked https://stackoverflow.com/a/9720733/80002 as the answer. Only, I have slightly modified it. There is no point to use DictReader if I am going to postprocess it anyway, so here is my modification of the Sven’s code:
r = csv.reader(open(r'd:\aaa.csv', 'rb'))
header = r.next()
converters = [converters_map[c] for c in header]
for row in r:
row = {title:converter(value) for title, converter, value in zip(header, converters, row)}
print row
If you have a dictionary of converter functions converting strings to the respective types, then all you need is
(Python 2.7. For earlier versions use
dict()instead of the dictionary comprehension.)You can wrap this code in a generator function (simply use
yield rowinstead ofprint row).