[英]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. 我想把一个python dict对象转换成它的等效字符串,如果它是作为html表单数据提交的话。
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! 谢谢!
Try urllib.parse.urlencode : 试试urllib.parse.urlencode :
>>> from urllib.parse import urlencode
>>> urlencode({'foo': 1, 'bar': 2})
'foo=1&bar=2'
For Python 2.7, you will encounter this error: 对于Python 2.7,您将遇到此错误:
>>> 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. 请改用urllib.urlencode 。
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'
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... 对于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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.