TIMEX
TIMEX

Reputation: 271704

How do I turn a dictionary into a string?

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

How can I turn that into a string:

fruit=orange&color=red&size=5

Upvotes: 1

Views: 893

Answers (4)

Mark Byers
Mark Byers

Reputation: 838116

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'

Upvotes: 11

Ants Aasma
Ants Aasma

Reputation: 54882

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

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

Upvotes: 2

S.Lott
S.Lott

Reputation: 391848

Are you asking about this?

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

Upvotes: 3

chradcliffe
chradcliffe

Reputation: 471

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.

Upvotes: 3

Related Questions