How to turn a dictionary into a string?

advertisements
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'