Ordering of urlencoded tuples incorrect

MRAB google at mrabarnett.plus.com
Thu Jan 15 20:25:39 EST 2009


benlucas99 at googlemail.com wrote:
> I'm having problems with the ordering of the tuples produced by
> urllib.urlencode.  Taking an example straight from the docs and so
> doing the following:
> 
> 	import urllib
> 	...
> 	params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
> 	print params
> 
> The documentation for urlencode( query[, doseq]) says: "The order of
> parameters in the encoded string will match the order of parameter
> tuples in the sequence" but I'm getting:
> 
> 	"eggs=2&bacon=0&spam=1"
> 
> Should this not produce: "spam=1&eggs=2&bacon=0" ?
> 
> I am seeing this "incorrect" result using Python 2.5.1 and
> ActivePython 2.3.2 (both on XP SP2).  What am I doing wrong?  I've
> been googling around for an answer but I'm a Python newbie and so
> don't know the ropes yet.
> 
You're passing a dict, which is unordered. It will accept a tuple or 
list of 2-tuples or a dict:

 >>> # tuple of 2-tuples
 >>> urllib.urlencode((('spam', 1), ('eggs', 2), ('bacon', 0)))
'spam=1&eggs=2&bacon=0'
 >>>
 >>> # list of 2-tuples
 >>> urllib.urlencode([('spam', 1), ('eggs', 2), ('bacon', 0)])
'spam=1&eggs=2&bacon=0'
 >>>
 >>> # dict
 >>> urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
'eggs=2&bacon=0&spam=1'

but I doubt the order will matter in practice.



More information about the Python-list mailing list