Reputation: 50372
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!
Upvotes: 13
Views: 7411
Reputation: 12174
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'
Upvotes: 2
Reputation: 1119
>>> from urllib.parse import urlencode
>>> urlencode({'foo': 1, 'bar': 2})
'foo=1&bar=2'
Upvotes: 20
Reputation: 63777
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'
Upvotes: 2