[Tutor] mapping header row to data rows in file
Sivaram Neelakantan
nsivaram.net at gmail.com
Wed Jun 26 19:51:56 CEST 2013
On Wed, Jun 26 2013,Peter Otten wrote:
[snipped 22 lines]
> zip() is a good starting point if you want to put the rows into dicts:
>
> def reader(instream):
> rows = (line.split() for line in instream)
> names = next(rows)
> return (dict(zip(names, values)) for values in rows)
>
> with open(FILENAME, "r") as f:
> for row in reader(f):
> print row["name"]
>
> If you are sure that the column headers are valid python identifiers you can
> alternatively use a namedtuple:
>
> from collections import namedtuple
>
> def reader(instream):
> rows = (line.split() for line in instream)
> names = next(rows)
> Row = namedtuple("Row", names)
> return (Row(*values) for values in rows)
>
> with open(FILENAME, "r") as f:
> for row in reader(f):
> print row.name
>
> You might also have a look at csv.DictReader.
[snipped 7 lines]
Thanks for your suggestions and examples, I'll try them out.
sivaram
--
More information about the Tutor
mailing list