params = {'fruit':'orange', 'color':'red', 'size':'5'}
How can I turn that into a string:
fruit=orange&color=red&size=5
params = {'fruit':'orange', 'color':'red', 'size':'5'}
How can I turn that into a string:
fruit=orange&color=red&size=5
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'
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
.
Are you asking about this?
>>> params = {'fruit':'orange', 'color':'red', 'size':'5'}
>>> import urllib
>>> urllib.urlencode( params )
'color=red&fruit=orange&size=5'
If you want to create a querystring, Python comes with batteries included:
import urllib
print(urllib.urlencode({'fruit':'orange', 'color':'red', 'size':'5'}))