views:

139

answers:

4
params = {'fruit':'orange', 'color':'red', 'size':'5'}

How can I turn that into a string:

fruit=orange&color=red&size=5
+11  A: 

You can do it like this:

'&'.join('%s=%s' % (k,v) for k,v in params.items())

If you are building strings for a URL it would be better to use urllib as this will escape correctly for you too:

>>> params = { 'foo' : 'bar+baz', 'qux' : 'quux' }
>>> urllib.urlencode(params)
'qux=quux&foo=bar%2Bbaz'
Mark Byers
+3  A: 

If you are encoding url parameters, you can use urllib.urlencode to accomplish this. For example:

import urllib
params = {'fruit':'orange', 'color':'red', 'size':'5'}
encoding = urllib.urlencode(params)

this will also run the dict through urllib.quote_plus.

chradcliffe
+3  A: 

Are you asking about this?

>>> params = {'fruit':'orange', 'color':'red', 'size':'5'}
>>> import urllib
>>> urllib.urlencode( params )
'color=red&fruit=orange&size=5'
S.Lott
+2  A: 

If you want to create a querystring, Python comes with batteries included:

 import urllib
 print(urllib.urlencode({'fruit':'orange', 'color':'red', 'size':'5'}))
Ants Aasma