简体   繁体   English

如何使用lambda函数将逗号分隔的键值对转换为字典

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

I'm having a little problem figuring out lamba functions. 我在找出lamba函数时遇到了一些问题。 Could someone show me how to split the following string into a dictionary using lambda functions? 有人可以告诉我如何使用lambda函数将以下字符串拆分成字典吗?

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

Thanks 谢谢

There is not really a need for a lambda here. 这里真的不需要lambda。

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: 您不需要lambda函数来执行此操作:

>>> 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! 如果你真的想要你甚至可以用两个lambdas做这个,但从来没有尝试过这个! 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(',')),
    {})                                                 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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