[Fixed]-How to parse URL encoded data recieved via POST

22👍

Python 2:

>>> from urlparse import parse_qs
>>> parse_qs('foo=spam&bar=answer&bar=42')
{'foo': ['spam'], 'bar': ['answer', '42']}

Python 3:

>>> from urllib.parse import parse_qs
>>> parse_qs('foo=spam&bar=answer&bar=42')
{'foo': ['spam'], 'bar': ['answer', '42']}

Both python 2/3:

>>> from six.moves.urllib.parse import parse_qs

UPD

There is also parse_qsl function that returns a list of two-items tuples, like

>>> parse_qsl('foo=spam&bar=answer&bar=42')
[('foo', 'spam'), ('bar', 'answer'), ('bar', '42')]

It is very suitable to passing such list to dict() constructor, meaning that you got a dict with only one value per name. Note that the last name/value pair takes precedence over early occurrences of same name (see dict in library reference).

Leave a comment