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

10,758

Solution 1

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

Solution 2

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'}
Share:
10,758
Mridang Agarwalla
Author by

Mridang Agarwalla

I'm a software developer who relishes authoring Java and Python, hacking on Android and toying with AppEngine. I have a penchant for development and a passion for the business side of software. In between all the work, I contribute to a number of open-source projects, learn to master the art of cooking Asian cuisine and try to stay sane while learning to fly my Align Trex-600 Nitro Heli.

Updated on June 04, 2022

Comments

  • Mridang Agarwalla
    Mridang Agarwalla almost 2 years

    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

  • Il-Bhima
    Il-Bhima almost 14 years
    You beat me to it with exactly the same code. :-) Deleting mine.