Url Query Parameters to Dict Python

URL query parameters to dict python

Use the urllib.parse library:

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

The urllib.parse.parse_qs() and urllib.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 called urlparse.

URL query parameter as a dictionary in Pyramid

If I understand what you are asking, an example is in the Pyramid Quick Tour with links to further examples and the complete Pyramid request API.

Essentially:

fields_articles = request.params.get('fields[articles]', 'No articles provided')
fields_people = request.params.get('fields[people]', 'No people provided')

Then put them into a dictionary.

EDIT

Would this suffice?

fields = {
'articles': request.params.get('fields[articles]', ''),
'people': request.params.get('fields[people]', ''),
}

Python Dictionary to URL Parameters

Here is the correct way of using it in Python 3.

from urllib.parse import urlencode
params = {'a':'A', 'b':'B'}
print(urlencode(params))

How to convert a dictionary to query string in Python?

Python 3

urllib.parse.urlencode(query, doseq=False, [...])

Convert a mapping object or a sequence of two-element tuples, which may contain str or bytes objects, to a percent-encoded ASCII text string.

— Python 3 urllib.parse docs

A dict is a mapping.

Legacy Python

urllib.urlencode(query[, doseq])

Convert a mapping object or a sequence of two-element tuples to a “percent-encoded” string... a series of key=value pairs separated by '&' characters...

— Python 2.7 urllib docs



Related Topics



Leave a reply



Submit