Fix Python – Python Dictionary to URL Parameters

Question

Asked By – kzh

I am trying to convert a Python dictionary to a string for use as URL parameters. I am sure that there is a better, more Pythonic way of doing this. What is it?

x = ""
for key, val in {'a':'A', 'b':'B'}.items():
    x += "%s=%s&" %(key,val)
x = x[:-1]

Now we will see solution for issue: Python Dictionary to URL Parameters


Answer

Here is the correct way of using it in Python 3.

from urllib.parse import urlencode
params = {'a':'A', 'b':'B'}
print(urlencode(params))

This question is answered By – Atharva

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0