fileinput.input, readlines and ...
Scott David Daniels
Scott.Daniels at Acm.Org
Wed Jun 24 12:37:57 EDT 2009
Peter Otten wrote:
> ...
> If you need more than a few name value pairs it pays to put the data in a
> dictionary first:
>
> # assuming that values always consist of a single line
> with open(filename) as instream:
> lines = (line.strip() for line in lines)
> lookup = dict(zip(lines, lines))
> print lookup["Data2"]
> print lookup["Data3"]
Little bit of a fluff-up here. Perhaps something like:
with open(filename) as instream:
lines = (line.strip() for line in instream)
lookup = dict(zip(lines[::2], lines[1::2]))
The other way to do it is:
lookup = {}
with open(filename) as instream:
gen = (line.strip() for line in instream)
for key in gen:
lookup[key] = next(gen)
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list