开发者

How to convert comma-separated key value pairs into a dictionary using lambda functions

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:d开发者_StackOverflow社区unno,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(',')),
    {})                                                 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜