How to convert a dictionary to a query string in Python?

After using cgi.parse_qs() , how to convert the result (dictionary) back to the query string? Search for something similar to urllib.urlencode() .

+79
python urllib2 urllib
18 Oct '11 at 3:10
source share
4 answers

Python 3

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

Convert the matching object or a sequence of two-element tuples that can contain str or bytes objects to an ASCII text string encoded in percent.

- Python 3 urllib.parse docs

dict is a mapping.

Python Legacy

urllib.urlencode ( query [, doseq ])
Convert a matching object or a sequence of two-element tuples to a string encoded in percent ... a series of key=value pairs separated by the characters '&' ...

- Python 2.7 urllib docs

+128
Oct 18 '11 at 3:13
source share

In python3, it is slightly different:

 from urllib.parse import urlencode urlencode({'pram1': 'foo', 'param2': 'bar'}) 

output: 'pram1=foo¶m2=bar'

for compatibility with python2 and python3, try the following:

 try: #python2 from urllib import urlencode except ImportError: #python3 from urllib.parse import urlencode 
+43
Jan 29 '16 at 4:13
source share

You are looking for something like urllib.urlencode() !

However, when you call parse_qs() (unlike parse_qsl() ), the dictionary keys are the unique names of the query variables, and the values ​​are lists of values ​​for each name.

To pass this information to urllib.urlencode() , you must "flatten" these lists. Here's how you can do this with a tuple capture list:

 query_pairs = [(k,v) for k,vlist in d.iteritems() for v in vlist] urllib.urlencode(query_pairs) 
+4
Oct 18 2018-11-11T00:
source share

Perhaps you are 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 converts it into a query string, like urlencode. It will add the final "&" to the query string, but return query[:-1] corrects this if this is a problem.

-one
Oct 18 '11 at 4:12
source share