string to dictionary

Carel Fellinger cfelling at iae.nl
Fri Mar 1 19:31:42 EST 2002


les ander <les_ander at yahoo.com> wrote:
> Hi, 
> i have a list of strings like this:

> aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3',...]

> i want to convert this to a dictionary with a_i -> b_i without
> using loops (it is trivial to do it with loops)
> i tried this 

> dict={}
> map(lambda x,d=dict: c=string.split(x), d[c[0]]=c[1], aList)

try:
   >>> map(lambda x: d.__setitem__(*x), [x.split() for x in aList])
   [None, None, None]
   >>> d
   {'a_3': 'b_3', 'a_2': 'b_2', 'a_1': 'b_1'}

of with 2.2:
   >>> d = dict([x.split() for x in aList])
   >>> d
   {'a_3': 'b_3', 'a_2': 'b_2', 'a_1': 'b_1'}
-- 
groetjes, carel



More information about the Python-list mailing list