Leonardo Andrade Leonardo Andrade - 1 year ago 89
Python Question

URL query parameters to dict python

Is there a way to parse a URL (with some python library) and return a python dictionary with the keys and values of a query parameters part of the URL?

For example:

url = "http://www.example.org/default.html?ct=32&op=92&item=98"

expected return:

{'ct':32, 'op':92, 'item':98}

Answer Source

Use the urlparse library.:

>>> import urlparse
>>> url = "http://www.example.org/default.html?ct=32&op=92&item=98"
>>> urlparse.urlsplit(url)
SplitResult(scheme='http', netloc='www.example.org', path='/default.html', query='ct=32&op=92&item=98', fragment='')
>>> urlparse.parse_qs(urlparse.urlsplit(url).query)
{'item': ['98'], 'op': ['92'], 'ct': ['32']}
>>> dict(urlparse.parse_qsl(urlparse.urlsplit(url).query))
{'item': '98', 'op': '92', 'ct': '32'}

The urlparse.parse_qs() and urlparse.parse_qsl() methods parse out query strings, taking into account that keys can occur more than once and that order may matter.

In Python 3, urlparse has been moved to urllib.parse.