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

MRAB python at mrabarnett.plus.com
Thu Jun 3 22:43:11 EDT 2010


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?
> 
> Greetings and thanks
> 
Split the string on the semicolons, then split each resulting string on
the equals, then pass the result to dict. You can use a generator
expression for this (or a list comprehension if it's an old version of
Python). If the string has a trailing semicolon then you should strip
that off first.

This all assumes that the values themselves don't contain semicolons or
equals.



More information about the Python-list mailing list