questions about how to parse a string and put it in a dictionary

Tim Chase python.list at tim.thechases.com
Fri Jun 4 08:28:45 EDT 2010


On 06/03/2010 09:21 PM, joblack wrote:
> I've got a string which (without any CR or LF) consists of
>
> 'attribute1=attribute_value;attribute2=attribute_value2; ...'
>
> and I want them to read in a dictionary so that the attribute name is
> the key and the attribute value is the data.
>
> Any ideas for an implementation?

While I agree with Bryan that this looks suspiciously like a URL 
query-string (and thus you likely want to use his suggestion for 
the built-in tools to parse them), I haven't seen the one-liner 
version float by, so here it is just for fun:

   s = "hello=world;this=that;foo=bar"
   results = dict((k,v) for (k,_,v) in (pair.partition('=') for 
pair in s.split(';')))

As Bryan cautions, URL query-strings can have multiple values for 
the same key, and your example doesn't address that case:

   foo=bar;foo=baz;hello=world;this=that

so the code examples you're getting don't address it either :)

-tkc








More information about the Python-list mailing list