fileinput.input, readlines and ...

Scott David Daniels Scott.Daniels at Acm.Org
Wed Jun 24 16:34:33 EDT 2009


Peter Otten wrote:
> Scott David Daniels wrote:
>> Peter Otten wrote:
>>> with open(filename) as instream:
>>>     lines = (line.strip() for line in lines)
>>>     lookup =  dict(zip(lines, lines))
> 
>> Little bit of a fluff-up here.  
> 
> Sorry, it should have been
> 
> with open(filename) as instream:
>     lines = (line.strip() for line in instream)
>     lookup =  dict(zip(lines, lines))
> 
>> Perhaps something like:
>>
>>      with open(filename) as instream:
>>          lines = (line.strip() for line in instream)
>>      lookup = dict(zip(lines[::2], lines[1::2]))
> 
> Tu quoque ;)

You are exactly right (and my vocabulary expands a bit); I must go
wipe the egg off of my face now.  I still am thinking lists even
though I am writing generators.  I should have written:
         with open(filename) as instream:
             lines = [line.strip() for line in instream]
         lookup = dict(zip(lines[::2], lines[1::2]))
But, your example does in fact work as written.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list