Python,反函数 urllib.urlencode

标签 python urllib

如何将urllib.urlencode处理后的数据转成dict? urllib.urldecode 不存在。

最佳答案

作为 the docs对于 urlencode 来说,

The urlparse module provides the functions parse_qs() and parse_qsl() which are used to parse query strings into Python data structures.

(在较早的 Python 版本中,它们位于 cgi 模块中)。所以,例如:

>>> 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']}

原始字典 d 和“往返”字典 d1 之间的明显区别在于后者具有(在这种情况下为单项)lists 作为值——这是因为在查询字符串中没有唯一性保证,并且对于您的应用来说,了解为每个键提供了哪些多个值可能很重要(也就是说,列表不会始终是单项的;-)。

作为替代方案:

>>> sq = urlparse.parse_qsl(s)
>>> sq  
[('a', 'b'), ('c', 'd')]
>>> dict(sq)
{'a': 'b', 'c': 'd'}

你可以得到一个对的序列(urlencode 也接受这样的参数——在这种情况下它保留了顺序,而在 dict 的情况下没有顺序可以保留;-)。如果您知道没有重复的“键”,或者不关心是否有,那么(如我所示)您可以调用 dict 来获取具有非列表值的字典。但是,一般而言,您确实需要考虑如果存在重复项 时要做什么(Python 不会代表您做出决定;-)。

关于Python,反函数 urllib.urlencode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3542881/

相关文章:

python - IPython Jupyter Notebook Latex 新页面

python - 为什么我的 contextmanager 函数不像 python 中的 contextmanager 类那样工作?

python - 值错误 : unknown url type

python - 从 Bittrex 解析 JSON

python-3.x - 使用 Pytest 在函数中引发的模拟异常

python - 如何在单个 catplot 图中绘制多个数据帧

Python图像分析: reading a multidimensional TIFF file from confocal microscopy

互联网连接中断的 Python 的 urllib.request.urlopen

python - 如何将http响应分成 block ?

Python - 使用 re.findall 中的\n 将列表写入文本文件