python中的urlencode多维字典
如何在 Python 中获取多维字典的 URL 编码版本?不幸的是,urllib.urlencode()
仅适用于单个维度。我需要一个能够对字典进行递归编码的版本。
例如,如果我有以下字典:
{'a': 'b', 'c': {'d': 'e'}}
我想获取以下字符串:
a=b&c[d]=e
How can I get a URL-encoded version of a multidimensional dictionary in Python? Unfortunately, urllib.urlencode()
only works in a single dimension. I would need a version capable of recursively encoding the dictionary.
For example, if I have the following dictionary:
{'a': 'b', 'c': {'d': 'e'}}
I want to obtain the following string:
a=b&c[d]=e
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
好的人们。我自己实现了它:
不过,我很想知道是否有更好的方法来做到这一点。我不敢相信 Python 的标准库没有实现这个。
OK people. I implemented it myself:
Still, I'd be interested to know if there's a better way to do this. I can't believe Python's standard library doesn't implement this.
像这样的东西吗?
Something like this?
基于@malaney的代码,我认为下面的代码很好地模拟了PHP函数
http_build_query()
。Based on the code of @malaney, I think that the code below emulates the PHP function
http_build_query()
quite well.我认为下面的代码可能是您想要的
输出,
它看起来像
PS:您可能需要使用
OrderDict
来替换上面的dict
I think the code below may be what you want
the output is
which is look like
PS: you may want use
OrderDict
to replacedict
above上述解决方案仅适用于深度 < 的数组。 2. 下面的代码将正确地对任意深度的多维数组进行urlencode。
The above solution only works for arrays with depth < 2. The code below will properly urlencode a multidimensional array of any depth.
函数 get_encoded_url_params() 将字典作为参数并返回字典的 url 编码形式。
The function get_encoded_url_params() takes a dict as argument and returns url encoded form of the dict.
json.dumps 和 json.loads 怎么样?
what about json.dumps and json.loads?
这个简化版本怎么样:
我同意不可读,也许使用 itertools.chain 而不是另一个列表理解可以更好地压平列表。
这只会更深一层,如果你添加一些逻辑来根据级别管理 N 个“[%s]”,你的可以更深 N 层,但我想这不是必要的
what about this simplified version:
I agree is not readable, maybe flattening the list can be better done with itertools.chain instead of another list comprehension.
This only goes 1 level deeper, yours can go N levels deeper if you would add some logic to manage N numbers of "[%s]" depending on the level, but I guess is not that necesary
如果你想将 python dict/list/nested 转换为 PHP 数组,如 urlencoded 字符串。
在Python中,大多数要转换为urlencoded的数据类型可能是:
dict
list
tuple
nested of them
,就像https://github.com/Viky-zhang/to_php_post_arr
PS 一些代码: https://stackoverflow.com/a/4014164/2752670
If you want to convert python dict/list/nested to PHP Array like urlencoded string.
In python, most of the data type you want to convert to urlencoded maybe:
dict
list
tuple
nested of them
, Likehttps://github.com/Viky-zhang/to_php_post_arr
P.S. some code from: https://stackoverflow.com/a/4014164/2752670