Best way to parse file into db-type layout?
Michael Hoffman
cam.ac.uk at mh391.invalid
Thu Apr 28 20:44:30 EDT 2005
Peter A. Schott wrote:
> I've got a file that seems to come across more like a dictionary from what I can
> tell. Something like the following format:
>
> ###,1,val_1,2,val_2,3,val_3,5,val_5,10,val_10
> ###,1,val_1,2,val_2,3,val_3,5,val_5,11,val_11,25,val_25,967,val_967
Peter, I'm not sure exactly what you want. Perhaps a dictionary for each
row in the file? Where the first row would result in:
{"letter_type": "###", 1: "val_1", 2: "val_2", 3: "val_3", 5: "val_5",
10: "val_10"}
Something like this:
import csv
import fileinput
row_dicts = []
for row in csv.reader(fileinput.input()):
row_dict = dict(letter_type=row[0])
for col_index in xrange(1, len(row), 2):
row_dict[int(row[col_index])] = row[col_index+1]
row_dicts.append(row_dict)
Someone else might come up with something more elegant.
--
Michael Hoffman
More information about the Python-list
mailing list