Ordering of urlencoded tuples incorrect

John Machin sjmachin at lexicon.net
Fri Jan 16 02:44:18 CET 2009


On Jan 16, 11:59 am, benluca... 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:

What are "the docs" you are reading that include such an example? The
docs distributed with Python 2.5.1 from www.python.org have only this:
"""
urlencode( query[, doseq])

Convert a mapping object or a sequence of two-element tuples to a
``url-encoded'' string, suitable to pass to urlopen() above as the
optional data argument. This is useful to pass a dictionary of form
fields to a POST request. The resulting string is a series of
key=value pairs separated by "&" characters, where both key and value
are quoted using quote_plus() above. If the optional parameter doseq
is present and evaluates to true, individual key=value pairs are
generated for each element of the sequence. When a sequence of two-
element tuples is used as the query argument, the first element of
each tuple is a key and the second is a value. The order of parameters
in the encoded string will match the order of parameter tuples in the
sequence. The cgi module provides the functions parse_qs() and
parse_qsl() which are used to parse query strings into Python data
structures.
"""

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

"query" can be either a mapping object (e.g. a dictionary, as you have
used) or a sequence of 2-tuples. No such guarantee as you quote above
can be made for a mapping; mappings are just not orderable.
If you want order, give it a sequence, like this:

| >>> import urllib
| >>> urllib.urlencode((('spam', 1), ('eggs', 2), ('bacon', 0)))
| 'spam=1&eggs=2&bacon=0'

HTH,
John



More information about the Python-list mailing list