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

Bryan bryanjugglercryptographer at yahoo.com
Thu Jun 3 23:29:01 EDT 2010


joblack wrote:
> I've got a string which (without any CR or LF) consists of
>
> 'attribute1=attribute_value;attribute2=attribute_value2; ...'

Technically that's short of a rigorous specification, but it sure
looks like a standard web "query string", the content type known as
"application/x-www-form-urlencoded". See:
http://en.wikipedia.org/wiki/Query_string

> 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?

Parsing query strings is already implemented (more than once) in
Python's standard library. In current Python 2.x, you might use
urlparse.parse_qs(). As in:

>>> from urlparse import parse_qs
>>>
>>> parse_qs('attribute1=attribute_value;attribute2=attribute_value2')
{'attribute2': ['attribute_value2'], 'attribute1':
['attribute_value']}

You'll note the values are lists, to handle the cases where a name is
equated to more than one simple value.


--
--Bryan Olson



More information about the Python-list mailing list