How to convert a dictionary to query string in Python?

Sam picture Sam · Oct 18, 2011 · Viewed 75.4k times · Source

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

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Oct 18, 2011

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.

Python 3 urllib.parse docs

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 of key=value pairs separated by '&' characters...

Python 2.7 urllib docs