Cleaner idiom for text processing?
Peter Hansen
peter at engcorp.com
Tue May 25 22:17:32 EDT 2004
Michael Ellis wrote:
> I have some data files with lines in space-delimited <name> <value>
> format. There are multiple name-value pairs per line.
>
> Is there a cleaner idiom than the following for reading each line into
> an associative array for the purpose of accessing values by name?
>
> 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'])
for line in infile:
tokens = line.split()
d = dict(zip(tokens[::2], tokens[1::2]))
do_something_with_values(...)
By the way, don't use "dict" as a variable name. It's already
a builtin factory function to create dictionaries.
-Peter
More information about the Python-list
mailing list