a clean way to define dictionary

Oren Tirosh oren-py-l at hishome.net
Thu Jun 19 06:20:48 EDT 2003


On Thu, Jun 19, 2003 at 09:16:17AM +0000, Kendear wrote:
> I'd prefer not to rely on the newline
> separating each key value pair or any limitation
> of the white spaces...  so i tried
> the following and they seem to work fine...
> 
> >>> lst = """
> a    1            b     1000
> foo  3            foo2  2000
> bar  234          bar2  1200
> joe  321          cool  2
> """
> 
> >>> lst = lst.split()
> 
> >>> dict([(lst[i], eval(lst[i+1])) for i in range(0, len(lst), 2)])
> {'a': 1, 'bar2': 1200, 'bar': 234, 'foo': 3, 'cool': 2, 'b': 1000, 'foo2': 
> 2000, 'joe': 321}
> 
> >>> dict([(lst.pop(0), eval(lst.pop(0))) for i in range(0, len(lst), 2)])
> {'a': 1, 'bar2': 1200, 'bar': 234, 'foo': 3, 'cool': 2, 'b': 1000, 'foo2': 
> 2000, 'joe': 321}
> 
> # or the above can be
> >>> dict([(lst.pop(0), eval(lst.pop(0))) for i in range(len(lst)/2)])
> {'a': 1, 'bar2': 1200, 'bar': 234, 'foo': 3, 'cool': 2, 'b': 1000, 'foo2': 
> 2000, 'joe': 321}

This version does the splitting into pairs in one step:

>>> dict([m.groups() for m in re.finditer(r'(\S+)\s+(\S+)', lst)])
{'a': '1', 'bar2': '1200', 'bar': '234', 'foo': '3', 'cool': '2', 'b':
'1000', 'foo2': '2000', 'joe': '321'}


This one does not create any temporary lists - pairs are streamed from 
finditer through the generator function straight into the dictionary:

>>> def genpairs(s):
...    for m in re.finditer(r'(\S+)\s+(\S+)', s):
...        yield m.groups()
...
>>> dict(genpairs(lst))
{'a': '1', 'bar2': '1200', 'bar': '234', 'foo': '3', 'cool': '2', 'b':
'1000', 'foo2': '2000', 'joe': '321'}


"There should be one-- and preferably only one --obvious way to do it."

;-)

    Oren






More information about the Python-list mailing list