混淆的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?
这看起来和我的元组顺序不一样。
3 个回答
1
为什么不使用 OrderedDict
呢?这样你的代码看起来会像这样:
from collections import OrderedDict
from urllib.parse import urlencode
d = OrderedDict()
d['one'] = 'one'
d['two'] = 'two'
d['three'] = 'three'
d['four'] = 'four'
...
data=urlencode(d)
print(data)
# one=one&two=two&three=three&four=four
这样的话,你的字典顺序就会被保留下来。
6
如果有人像我一样来到这里,想找一种方法让urlencode
的结果是确定性的,也就是说每次得到的结果都是一样的,想要按字母顺序编码值,可以这样做:
from urllib.parse import urlencode
values ={'one':'one',
'two':'two',
'three':'three',
'four':'four',
'five':'five',
'six':'six',
'seven':'seven'}
sorted_values = sorted(values.items(), key=lambda val: val[0])
data=urlencode(sorted_values)
print(data)
#> 'five=five&four=four&one=one&seven=seven&six=six&three=three&two=two'
27
字典本身是无序的,这是因为它们的实现方式。如果你想要有序的结构,可以使用元组的列表(或者列表的元组,或者元组的元组,或者列表的列表……)来代替:
values = [ ('one', 'one'), ('two', 'two') ... ]