3

I am trying to simulate a get request with python. I have a dictionary of parameters and am using urllib.urlencode to urlencode them

I notice that although the dictionary is of the form:

{ "k1":"v1", "k2":"v2", "k3":"v3", .. }

upon urlencoding the order of the parameters is switched to:

/?k1=v1&k3=v3%k2=v2...

why does this happen and can I force the order in the dictionary to stay the same?

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • 2
    All are passed as `GET` parameters, and order does not matter until `key` and its `value` gets interchanged. – Yogeesh Seralathan Aug 03 '14 at 18:19
  • this behavior comes from the fact that dictionary is a hash table. then keys are not ordered. see http://stackoverflow.com/questions/4458169/in-what-order-does-python-display-dictionary-keys – philippe lhardy Aug 03 '14 at 18:20

1 Answers1

8

As you can see in the comments, Python dictionaries are not ordered, but there is an OrderedDict in Python that you can use to achieve the result you want:

from collections import OrderedDict
import urllib
urllib.urlencode(OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]))
# Out: 'k1=v1&k2=v2&k3=v3'

More info about OrderedDIct

Diego Navarro
  • 9,316
  • 3
  • 26
  • 33