Cleaner idiom for text processing?

Peter Otten __peter__ at web.de
Wed May 26 03:25:17 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'])

Yet another way to create the dictionary:

>>> import itertools
>>> nv = iter("foo 1 bar 2 baz 3\n".split())
>>> dict(itertools.izip(nv, nv))
{'baz': '3', 'foo': '1', 'bar': '2'}
>>>

Peter




More information about the Python-list mailing list