string to dictionary

Bernard Yue bernie at 3captus.com
Fri Mar 1 20:13:27 EST 2002


les ander 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)

map(lambda x,d=dict: c=string.split(x), d[c[0]]=c[1], aList)
                      ^                 ^    
First, assignment is not allowed within lambda.  Secondly, the scope of
lambda ends at the first comma (correct me if I were wrong).  Hence
d[c[0]=c[1] become a list and since c is not defined outside lambda, the
error message resulted.

The following code should work:

>>> aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3']
>>> dict = {}
>>> map( lambda x, d=dict: d.update( {x.split()[0] : x.split()[1]}), aList)
[None, None, None]
>>> dict
{'a_1': 'b_1', 'a_2': 'b_2', 'a_3': 'b_3'}
>>> 

I would like to see a better solution as I find using split() twice ugly

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


Bernie

-- 
There are three schools of magic.  One:  State a tautology, then ring
the changes on its corollaries; that's philosophy.  Two:  Record many
facts.  Try to find a pattern.  Then make a wrong guess at the next
fact; that's science.  Three:  Be aware that you live in a malevolent
Universe controlled by Murphy's Law, sometimes offset by Brewster's
Factor; that's engineering.  So far as I can remember, there is not one
word in the Gospels in praise of intelligence.

                -- Bertrand Russell



More information about the Python-list mailing list