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}
Use the
urllib.parse
library:The
urllib.parse.parse_qs()
andurllib.parse.parse_qsl()
methods parse out query strings, taking into account that keys can occur more than once and that order may matter.If you are still on Python 2,
urllib.parse
was calledurlparse
.If you prefer not to use a parser:
So I won't delete what's above but it's definitely not what you should use.
I think I read a few of the answers and they looked a little complicated, incase you're like me, don't use my solution.
Use this:
and for Python 2.X
I know this is the same as the accepted answer, just in a one liner that can be copied.
For python 2.7
For Python 3, the values of the dict from
parse_qs
are in a list, because there might be multiple values. If you just want the first one:I agree about not reinventing the wheel but sometimes (while you're learning) it helps to build a wheel in order to understand a wheel. :) So, from a purely academic perspective, I offer this with the caveat that using a dictionary assumes that name value pairs are unique (that the query string does not contain multiple records).
I'm using version 3.6.5 in the Idle IDE.