Python,相反的函数 urllib.urlencode [英] Python, opposite function urllib.urlencode
问题描述
如何将urllib.urlencode
处理后的数据转换为dict?urllib.urldecode
不存在.
As theurlencode
的文档 说,
urlparse 模块提供了函数 parse_qs() 和 parse_qsl()用于解析查询字符串转化为 Python 数据结构.
(在较旧的 Python 版本中,它们位于 cgi
模块中).因此,例如:
原始字典 d
和往返"字典 d1
之间的明显区别在于后者具有(在这种情况下为单个项目)lists 作为值——这是因为在查询字符串中没有唯一性保证,并且您的应用程序了解每个键的多个值可能很重要(也就是说,列表不会永远是单项的;-)
作为替代:
<预><代码>>>>sq = urlparse.parse_qsl(s)>>>平方[('A B C D')]>>>字典(平方米){'A B C D'}您可以获得一系列对(urlencode 也接受这样的参数——在这种情况下它保留顺序,而在 dict 情况下没有保留顺序;-).如果您知道没有重复的键",或者不关心是否有重复的键",那么(正如我所展示的)您可以调用 dict
来获取具有非列表值的字典.但是,一般而言,您确实需要考虑如果存在重复项,您想做什么(Python 不会代表您做出决定;-).
How can I convert data after processing urllib.urlencode
to dict?
urllib.urldecode
does not exist.
As the docs for urlencode
say,
The urlparse module provides the functions parse_qs() and parse_qsl() which are used to parse query strings into Python data structures.
(In older Python releases, they were in the cgi
module). So, for example:
>>> import urllib
>>> import urlparse
>>> d = {'a':'b', 'c':'d'}
>>> s = urllib.urlencode(d)
>>> s
'a=b&c=d'
>>> d1 = urlparse.parse_qs(s)
>>> d1
{'a': ['b'], 'c': ['d']}
The obvious difference between the original dictionary d
and the "round-tripped" one d1
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:
>>> sq = urlparse.parse_qsl(s)
>>> sq
[('a', 'b'), ('c', 'd')]
>>> dict(sq)
{'a': 'b', 'c': 'd'}
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,相反的函数 urllib.urlencode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!