Python Dictionary for URL Parameters

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 to do this. What is it?

x = "" for key, val in {'a':'A', 'b':'B'}.items(): x += "%s=%s&" %(key,val) x = x[:-1] 
+92
python dictionary url-parameters
Aug 05 '09 at 14:14
source share
3 answers

Use urllib.urlencode() . It takes a dictionary of key-value pairs and converts it into a form suitable for the URL (for example, key1=val1&key2=val2 ).

If you are using Python3, use urllib.parse.urlencode()

If you want to create a URL with duplicate parameters, for example: p=1&p=2&p=3 , you have two options:

 >>> import urllib >>> a = (('p',1),('p',2), ('p', 3)) >>> urllib.urlencode(a) 'p=1&p=2&p=3' 

or if you want to create a url with duplicate parameters:

 >>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True) 'p=1&p=2&p=3' 
+187
Aug 05 '09 at 14:16
source share

Use a third-party Python furl URL manipulation library:

 f = furl.furl('') f.args = {'a':'A', 'b':'B'} print(f.url) # prints ... '?a=A&b=B' 

If you need duplicate options, you can do the following:

 f = furl.furl('') f.args = [('a', 'A'), ('b', 'B'),('b', 'B2')] print(f.url) # prints ... '?a=A&b=B&b=B2' 
+1
Dec 02 '16 at 9:02
source share

For me, this looks a bit more Pythonic and does not use any other modules:

 x = '&'.join(["{}={}".format(k, v) for k, v in {'a':'A', 'b':'B'}.items()]) 
-5
May 19 '17 at 19:27
source share



All Articles