Python,相反函数 urllib.urlencode
处理urllib.urlencode
后的数据如何转换为dict? urllib.urldecode
不存在。
How can I convert data after processing urllib.urlencode
to dict?urllib.urldecode
does not exist.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
urllib.unquote_plus()
做你想做的事。它将 %xx 转义符替换为其单字符等效项,并将加号替换为空格。示例:
产量
urllib.unquote_plus()
does what you want. It replaces %xx escapes by their single-character equivalent and replaces plus signs with spaces.Example:
yields
正如
urlencode
的文档所说,(在较旧的 Python 版本中,它们位于
cgi
模块中)。因此,例如:原始字典
d
和“往返”字典d1
之间的明显区别在于后者具有(在本例中为单项) 列出作为值——这是因为查询字符串中没有唯一性保证,并且对于您的应用来说,了解为每个键指定了哪些多个值可能很重要(也就是说,列表获胜)并不总是单项的;-)。作为替代方案:
您可以获得一系列对(urlencode 也接受这样的参数 - 在这种情况下它保留顺序,而在 dict 情况下没有顺序可以保留;-)。如果您知道没有重复的“键”,或者不关心是否有重复的“键”,那么(如我所示)您可以调用 dict 来获取包含非列表值的字典。然而,一般来说,您确实需要考虑如果存在重复项,您想要做什么(Python 不会代表您决定;-)。
As the docs for
urlencode
say,(In older Python releases, they were in the
cgi
module). So, for example:The obvious difference between the original dictionary
d
and the "round-tripped" oned1
is that the latter has (single-item, in this case) lists as values -- that's because there is no uniqueness guarantee in query strings, and it may be important to your app to know about what multiple values have been given for each key (that is, the lists won't always be single-item ones;-).As an alternative:
you can get a sequence of pairs (urlencode accepts such an argument, too -- in this case it preserves order, while in the dict case there's no order to preserve;-). If you know there are no duplicate "keys", or don't care if there are, then (as I've shown) you can call
dict
to get a dictionary with non-list values. In general, however, you do need to consider what you want to do if duplicates are present (Python doesn't decide that on your behalf;-).Python 3 版本 基于 Alex 的答案:
替代方案:
parse_qsl 是可逆的:
在解析用户输入时,请记住可能的重复项:
parse_qs
结果中的列表可能有多个项目parse_qsl
上调用dict
> 结果可能隐藏值Python 3 version based on Alex's answer:
The alternative:
parse_qsl is reversible:
Keep possible duplicates in mind, when parsing user-input:
parse_qs
result may have more than one itemdict
on theparse_qsl
result may hide values