After using cgi.parse_qs(), how to convert the result (dictionary) back to query string? Looking for something similar to urllib.urlencode().
4 Answers
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=valuepairs separated by'&'characters...
9 Comments
dict returned by cgi.parse_qs() actually has lists as its "values". Passing these straight in will result in very odd looking query strings.In python3, slightly different:
from urllib.parse import urlencode
urlencode({'pram1': 'foo', 'param2': 'bar'})
output: 'pram1=foo¶m2=bar'
for python2 and python3 compatibility, try this:
try:
#python2
from urllib import urlencode
except ImportError:
#python3
from urllib.parse import urlencode
Comments
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)
2 Comments
doseq=True.Maybe you're looking for something like this:
def dictToQuery(d):
query = ''
for key in d.keys():
query += str(key) + '=' + str(d[key]) + "&"
return query
It takes a dictionary and convert it to a query string, just like urlencode. It'll append a final "&" to the query string, but return query[:-1] fixes that, if it's an issue.
5 Comments
str.join() yet? How about urllib.quote_plus()?urlencode in urllib.py (it should by in your Python install) to see why creating a query string is sometimes not quite as simple as your answer implies (in particular the need to 'quote' certain characters that aren't valid in a URL). @Ignacio has also referenced two functions that would clean up your implementation and make it correct.from urllib.parse import urlencode; urlencode(your_dict)) is shorter and easier than this! I'll grant that it's sometimes smart to reinvent the wheel, even shoddily, when it's expensive or inconvenient to access existing, well-designed wheels, but here using the off-the-shelf wheel is easier and quicker than rolling your own inferior one.
cgi.parse_qs()is deprecated. Use urlparse.parse_qs() instead.