Transform a python dict into string compatible with Content-Type:“application/x-www-form-urlencoded”

StackOverflow https://stackoverflow.com/questions/8514988

  •  17-03-2021
  •  | 
  •  

Question

I'd like to take a python dict object and transform it into its equivalent string if it were to be submitted as html form data.

The dict looks like this:

{
   'v_1_name':'v_1_value'
  ,'v_2_name':'v_2_value'
}

I believe the form string should look something like this:

v_1_name=v_1_value&v_2_name=v_2_value

What is a good way to do this?

Thanks!

Was it helpful?

Solution

Try urllib.parse.urlencode:

>>> from urllib.parse import urlencode
>>> urlencode({'foo': 1, 'bar': 2})
'foo=1&bar=2'

OTHER TIPS

Simply iterte over the items, join the key and value and create a key/value pair separated by '=' and finally join the pairs by '&'

For Ex...

If d={'v_1_name':'v_1_value','v_2_name':'v_2_value','v_3_name':'v_3_value'}

Then

'&'.join('='.join([k,v]) for k,v in d.iteritems())

is

'v_2_name=v_2_value&v_1_name=v_1_value&v_3_name=v_3_value'

For Python 2.7, you will encounter this error:

>>> from urllib.parse import urlencode
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named parse

Use urllib.urlencode instead.

from urllib import urlencode
d = {'v_1_name': 'v_1_value', 'v_2_name': 'v_2_value'}
print urlencode(d)

Output

'v_2_name=v_2_value&v_1_name=v_1_value'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top