Cleaner idiom for text processing?

Peter Hansen peter at engcorp.com
Wed May 26 19:57:41 EDT 2004


Paul Rubin wrote:

> mellis at frogwing.com (Michael Ellis) writes:
> 
>>for line in infile:
>>   tokens = line.split()
>>   dict = {}
>>   for i in range(0, len(tokens),2) dict[tokens[i]] = tokens[i+1]
>>   do_something_with_values(dict['foo'],dict['bar'])
> 
> 
> Here's a pessimized version:
> 
>     for line in infile:
>        tokens = line.split()
>        d = {}
>        while tokens:
>           name = tokens.pop(0)
>           value = tokens.pop(0)
>           d[name] = value
>        do_something_with_values(dict['foo'],dict['bar'])

Paul, I don't understand why you say "pessimized".
The only potential flaw in the original and most
(all) of the other solutions seems to be present
in yours as well: if there are an odd number of
tokens on a line an exception will be raised.

-Peter



More information about the Python-list mailing list