SZC’s Agglomeration

{an agglomeration of laconic notes in relation to anything that sparks my interest}

Python :: Mapping a string to a dictionary

Posted by Stefan Camilleri on {2009.February.9}

/** Today at work I had to find a neat way of mapping a string of parameters into a usable dictionary in Python.  Searching on the web didn’t reveal any results, so I had to get my hands dirty and figure it out for myself  */ {

The data provided is in the form of a string “option1=1 option2=2 option3=3″

The solution is quite neat and simple too…

value = “option1=1 option2=2 option3=3″

dict( map( lambda x: x.split(“=”), value.split()) ) )

Essentially this produces a list of lists which is then fed to the dict function as follows:

[['option1','1'],['option2','2'],['option3','3']]

Simple :)

}

2 Responses to “Python :: Mapping a string to a dictionary”

  1. nice :)
    still it’s dirty… it’s python :) joking :)

  2. Interesting! I’m still a Python newbie and was questioning the utility of map()
    It’s clear to me now :)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>