'Transform a python dict into string compatible with Content-Type:"application/x-www-form-urlencoded"
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!
Solution 1:[1]
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'
Solution 2:[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'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhijit |
| Solution 2 | Joseph D. |
