Python Dictionary to URL Parameters
Use urllib.parse.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
).
For your example:
>>> import urllib.parse
>>> params = {'a':'A', 'b':'B'}
>>> urllib.parse.urlencode(params)
'a=A&b=B'
If you want to make a URL with repetitive params such as: p=1&p=2&p=3
you have two options:
>>> a = (('p',1),('p',2), ('p', 3))
>>> urllib.parse.urlencode(a)
'p=1&p=2&p=3'
or:
>>> urllib.parse.urlencode({'p': [1, 2, 3]}, doseq=True)
'p=1&p=2&p=3'
If you are still using Python 2, use urllib.urlencode()
.
For python 3, the urllib
library has changed a bit, now you have to do:
from urllib.parse import urlencode
params = {'a':'A', 'b':'B'}
urlencode(params)