a clean way to define dictionary

Kendear kendear at nospam.com
Thu Jun 19 11:16:17 CEST 2003


Alex Martelli wrote:
 > for key, value in [ [lst[i],list[i+1]] for i in range(0,len(lst),2) ]:
 >
 > or, as others have indicated, in Python 2.3 you could slice lst[::2]
 > and lst[1::2] to get the even and odd items and zip them up again:
 >
 > for key, value in zip(lst[::2], lst[1::2]):

thanks very much for all the hints...
they have helped a lot.

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}






More information about the Python-list mailing list