令人困惑的 python urlencode 顺序
好的,根据 http://docs.python.org/library/urllib.html
“编码字符串中参数的顺序将与序列中参数元组的顺序匹配。”
除非我尝试运行此代码:
import urllib
values ={'one':'one',
'two':'two',
'three':'three',
'four':'four',
'five':'five',
'six':'six',
'seven':'seven'}
data=urllib.urlencode(values)
print data
输出为...
seven=seven&six=six&three=three&two=two&four=four&five=five&one=one
7,6,3,2,4,5,1?
这看起来不像我的元组的顺序。
okay, so according to http://docs.python.org/library/urllib.html
"The order of parameters in the encoded string will match the order of parameter tuples in the sequence."
except when I try to run this code:
import urllib
values ={'one':'one',
'two':'two',
'three':'three',
'four':'four',
'five':'five',
'six':'six',
'seven':'seven'}
data=urllib.urlencode(values)
print data
outputs as ...
seven=seven&six=six&three=three&two=two&four=four&five=five&one=one
7,6,3,2,4,5,1?
That doesn't look like the order of my tuples.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于字典的实现方式,它们本质上是无序的。如果您希望对它们进行排序,则应该使用元组列表(或列表元组,或元组元组,或列表列表...):
Dictionaries are inherently unordered because of the way they are implemented. If you want them to be ordered, you should use a list of tuples instead (or a tuple of lists, or a tuple of tuples, or a list of lists...):
以防万一有人像我一样到达这里寻找一种从 urlencode 获取确定性结果的方法,按字母顺序对值进行编码,您可以这样做:
Just in case someones arrives here like me searching for a way to get deterministic results from
urlencode
, to encode the values alphabetically you can do it like this:为什么不使用OrderedDict?您的代码将如下所示:
这样您的字典的顺序将被保留
Why not using
OrderedDict
? Your code would then look like this:This way the order of your dictionary would be preserved