How to convert a dictionary to query string in Python?

PythonUrllib2Urllib

Python Problem Overview


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

Python Solutions


Solution 1 - 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.

> — 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

Solution 2 - Python

In python3, slightly different:

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

output: 'pram1=foo&param2=bar'

for python2 and python3 compatibility, try this:

try:
    #python2
    from urllib import urlencode
except ImportError:
    #python3
    from urllib.parse import urlencode

Solution 3 - Python

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)

Solution 4 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamView Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PythonJohnny ZhaoView Answer on Stackoverflow
Solution 3 - PythonJohnsywebView Answer on Stackoverflow
Solution 4 - PythongarbadosView Answer on Stackoverflow