11

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!

Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258

3 Answers3

17

Try urllib.parse.urlencode:

>>> from urllib.parse import urlencode
>>> urlencode({'foo': 1, 'bar': 2})
'foo=1&bar=2'
bcb
  • 1,977
  • 2
  • 22
  • 21
Frank Fang
  • 1,069
  • 8
  • 5
2

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'
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
2

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'
Abhijit
  • 62,056
  • 18
  • 131
  • 204