简体   繁体   English

在Python中确定性地将字典编码为url参数列表

[英]Deterministically encode a dictionary as a url parameter list in Python

I'm using urllib.parse.urlencode to generate the parameters string of a url. 我正在使用urllib.parse.urlencode生成url的参数字符串。 The input to the function is a dictionary. 该函数的输入是字典。 The problem with calling urlencode on a dictionary is that the output is not deterministic. 在字典上调用urlencode的问题是输出不确定。 Namely, the order of the parameters in the resulting string is not consistent. 即,结果字符串中参数的顺序不一致。 The undeterministic behavior of urlencode makes it hard to test pieces of code that use it. urlencode行为不确定,因此很难测试使用它的代码段。 Is there a deterministic equivalent of urlencode ? 是否存在urlencode的确定性等效项?

My current solution is to transform the dictionary into a list of tuples, sort it and then iterate the sorted list and generate the string. 我当前的解决方案是将字典转换成元组列表,对其进行排序,然后迭代排序后的列表并生成字符串。 I'm asking whether such a function already exists. 我问这样的功能是否已经存在。

urllib.parse.urlencode accepts not only mapping (dictionary), but also a sequence of two-element tuple: urllib.parse.urlencode不仅接受映射(字典),而且接受两个元素的元组序列:

>>> import urllib.parse
>>> urllib.parse.urlencode([('a', 'b'), ('c', 'd')])
'a=b&c=d'
>>> urllib.parse.urlencode([('c', 'd'), ('a', 'b')])
'c=d&a=b'

If instead you just need an ordered mapping, use collections.OrderedDict instead. 相反,如果您只需要有序映射,则使用collections.OrderedDict

If you have to use dicts then you can convert them to an OrderedDict before passing them to urlencode : 如果必须使用字典,则可以在将它们传递给urlencode之前将它们转换为OrderedDict

d = {'a': 1, 'b': 2}
urlencode(OrderedDict(sorted(d.items())))

This will convert the dict to the ordered two-element tuple falsetru mentions. 这会将dict转换为有序的两个元素的元组falsetru。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM