Tangled python urlencode order

okay so according to http://docs.python.org/library/urllib.html

"The order of the parameters in the encoded string will correspond to the order of the tuples of parameters 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

displayed as ...

seven=seven&six=six&three=three&two=two&four=four&five=five&one=one

7,6,3,2,4,5,1?

This is not like the order of my tuples.

+5
source share
3 answers

Dictionaries are inherently disordered due to how they are implemented. If you want them to be ordered, you should instead use a list of tuples (or a tuple of lists or a tuple of tuples or a list of lists ...):

values = [ ('one', 'one'), ('two', 'two') ... ]
+22
source

, - , , 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'
+5

Why not use OrderedDict? Your code will look like this:

from collections import OrderedDict

d = OrderedDict()
d['one'] = 'one'
d['two'] = 'two'
d['three'] = 'three'
d['four'] = 'four'
...

# Outputs "one one", "two two", "three three", "four four", ...
for key in d:
    print(key, d[key])

Thus, the order of your dictionary will be saved

0
source

All Articles