简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM