views:

58

answers:

3

I'm having a little problem figuring out lamba functions. Could someone show me how to split the following string into a dictionary using lambda functions?

fname:John,lname:doe,mname:dunno,city:Florida

Thanks

+3  A: 

There is not really a need for a lambda here.

s = "fname:John,lname:doe,mname:dunno,city:Florida"
sd = dict(u.split(":") for u in s.split(","))
Space_C0wb0y
You beat me to it with exactly the same code. :-) Deleting mine.
Il-Bhima
A: 

You don't need lambda functions to do this:

>>> s = "fname:John,lname:doe,mname:dunno,city:Florida"
>>> dict(item.split(":") for item in s.split(","))
{'lname': 'doe', 'mname': 'dunno', 'fname': 'John', 'city': 'Florida'}

But you can if you really want to:

>>> dict(map(lambda x: x.split(":"), s.split(",")))
{'lname': 'doe', 'mname': 'dunno', 'fname': 'John', 'city': 'Florida'}
Dave Kirby
A: 

If you really want you can even do this with two lambdas, but never try this at work! Just for fun:

s = "name:John,lname:doe,mname:dunno,city:Florida"
d = reduce(lambda d, kv: d.__setitem__(kv[0], kv[1]) or d, 
    map(lambda s: s.split(':'), s.split(',')),
    {})                                                 
Rorick