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.
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 ofkey=value
pairs separated by'&'
characters...
In python3, slightly different:
from urllib.parse import urlencodeurlencode({'pram1': 'foo', 'param2': 'bar'})
output: 'pram1=foo¶m2=bar'
for python2 and python3 compatibility, try this:
try: #python2 from urllib import urlencodeexcept ImportError: #python3 from urllib.parse import urlencode
You're looking for something exactly like urllib.urlencode()
!
However, when you call parse_qs()
(distinct from parse_qsl()
), the dictionary keys are the unique query variable names and the values are lists of values for each name.
In order to pass this information into urllib.urlencode()
, you must "flatten" these lists. Here is how you can do it with a list comprehenshion of tuples:
query_pairs = [(k,v) for k,vlist in d.iteritems() for v in vlist]urllib.urlencode(query_pairs)