string to dictionary

Raymond Hettinger python at rcn.com
Sat Mar 2 02:45:21 EST 2002


"les ander" <les_ander at yahoo.com> wrote in message
news:a2972632.0203011522.16f1b8e0 at posting.google.com...
> 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)



This ought to do it:
>>> aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3']
>>> dict(map(lambda g: g.split() ,aList))
{'a_3': 'b_3', 'a_2': 'b_2', 'a_1': 'b_1'}


If you don't have Python 2.2, then build the dictionary directly:
>>> d = {}
>>> map( lambda (k,v): d.__setitem__(k,v), map(string.split, aList) )
[None, None, None]
>>> d
{'a_3': 'b_3', 'a_2': 'b_2', 'a_1': 'b_1'}

Note, the use of __setitem__ to avoid '='.
Still, it's better to get Python 2.2 and avoid the second
method.  Good functional style stays away from
lambdas with side-effects (setting the dictionary).



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



I recommend:
1. Never use an assignment inside a lambda expression
2. Never name a dictionary 'dict' which overrides the constructor
3. If lambdas get confusing, write a simple, working 'def' first
    and use that in the map.



> but it complains that "keyword can't be an expression"
> can someone please help me get this right?
> thanks
> les


Good luck,


Raymond Hettinger





More information about the Python-list mailing list