Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse query string with urllib in Python 2.4

Using Python2.4.5 (don't ask!) I want to parse a query string and get a dict in return. Do I have to do it "manually" like follows?

>>> qs = 'first=1&second=4&third=3'
>>> d = dict([x.split("=") for x in qs.split("&")])
>>> d
{'second': '4', 'third': '3', 'first': '1'}

Didn't find any useful method in urlparse.

like image 605
Johannes Charra Avatar asked Nov 20 '09 10:11

Johannes Charra


People also ask

What is Urllib parse?

Source code: Lib/urllib/parse.py. This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.”

What is Parse_qs?

parse_qs. Parse a query string part of a URL, returning a dictionary of the data. Often used in conjunction with urlparse as it does not find the query string part of a URL on its own.


1 Answers

You have two options:

>>> cgi.parse_qs(qs)
{'second': ['4'], 'third': ['3'], 'first': ['1']}

or

>>> cgi.parse_qsl(qs)
[('first', '1'), ('second', '4'), ('third', '3')]

The values in the dict returned by cgi.parse_qs() are lists rather than strings, in order to handle the case when the same parameter is specified several times:

>>> qs = 'tags=python&tags=programming'
>>> cgi.parse_qs(qs)
{'tags': ['python', 'programming']}
like image 159
Pär Wieslander Avatar answered Sep 28 '22 03:09

Pär Wieslander