开发者

confusing python urlencode order

开发者 https://www.devze.com 2023-01-08 22:19 出处:网络
okay, s开发者_如何学Pythono 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.\"

okay, s开发者_如何学Pythono 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.


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...):

values = [ ('one', 'one'), ('two', 'two') ... ]


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:

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'


Why not using OrderedDict? Your code would then look like this:

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

This way the order of your dictionary would be preserved

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号