Python Dictionary to URL Parameters Python Dictionary to URL Parameters python python

Python Dictionary to URL Parameters


Use urllib.urlencode(). It takes a dictionary of key-value pairs, and converts it into a form suitable for a URL (e.g., key1=val1&key2=val2).

If you are using Python3, use urllib.parse.urlencode()

If you want to make a URL with repetitive params such as: p=1&p=2&p=3 you have two options:

>>> import urllib>>> a = (('p',1),('p',2), ('p', 3))>>> urllib.urlencode(a)'p=1&p=2&p=3'

or if you want to make a url with repetitive params:

>>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True)'p=1&p=2&p=3'


For python 3, the urllib library has changed a bit, now you have to do:

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


Use the 3rd party Python url manipulation library furl:

f = furl.furl('')f.args = {'a':'A', 'b':'B'}print(f.url) # prints ... '?a=A&b=B'

If you want repetitive parameters, you can do the following:

f = furl.furl('')f.args = [('a', 'A'), ('b', 'B'),('b', 'B2')]print(f.url) # prints ... '?a=A&b=B&b=B2'