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
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
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(","))
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'}
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(',')),
{})