如何在Python中将字典转换为查询字符串?
使用cgi.parse_qs()
后,如何将结果(字典)转换回查询字符串?寻找类似于 urllib.urlencode() 的东西。
After using cgi.parse_qs()
, how to convert the result (dictionary) back to query string? Looking for something similar to urllib.urlencode()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
蟒蛇3
dict
是一个映射。遗留Python
Python 3
A
dict
is a mapping.Legacy Python
在 python3 中,略有不同:
输出:
'pram1=foo¶m2=bar'
对于 python2 和 python3 兼容性,请尝试以下操作:
In python3, slightly different:
output:
'pram1=foo¶m2=bar'
for python2 and python3 compatibility, try this:
您正在寻找完全类似
urllib.urlencode()
的东西!但是,当您调用
parse_qs()
(与parse_qsl()
),字典键是唯一的查询变量名称,值是每个名称的值列表。为了将此信息传递到
urllib.urlencode()
,您必须“展平”这些列表。以下是如何使用元组的列表理解来做到这一点:You're looking for something exactly like
urllib.urlencode()
!However, when you call
parse_qs()
(distinct fromparse_qsl()
), the dictionary keys are the unique query variable names and the values are lists of values for each name.In order to pass this information into
urllib.urlencode()
, you must "flatten" these lists. Here is how you can do it with a list comprehenshion of tuples:也许您正在寻找这样的东西:
它需要一个字典并将其转换为查询字符串,就像 urlencode 一样。它将附加最后一个“&”到查询字符串,但
return query[:-1]
解决了这个问题(如果有问题)。Maybe you're looking for something like this:
It takes a dictionary and convert it to a query string, just like urlencode. It'll append a final "&" to the query string, but
return query[:-1]
fixes that, if it's an issue.