PEP 222 draft

Oleg Broytmann phd at phd.pp.ru
Thu Dec 28 09:59:47 EST 2000


Hi!

On Thu, 28 Dec 2000, Michael [iso-8859-1] StrЖder wrote:
> tlownds at my-deja.com wrote:
> >
> > In article <slrn947bj1.1rs.amk at 207-172-57-45.s45.tnt2.ann.va.dialup.rcn.com>,
> >   akuchlin at mems-exchange.org wrote:
> > >     Utility function: build a query string from a list of 2-tuples
> > >
> >
> > Perhaps it would be better to extend urllib.urlencode to handle this
> > case. I think it should be extended to handle lists as values as well:
> >
> > >>> urlencode({'x': ['a', 'b']})
> > 'x=%5b%27a%27,+%27b%27%5d'
> >
> > would be:
> >
> > 'x=a&x=b'
>
> But you can do that with a list of 2-tuples either. Note: The list
> order of dictionary keys is normally not preserved.

   Not so long ago I wrote such function and sent it to Guido (it was the
time before Python 1.6) and GvR rejected my code saying something like "it
is rare need for someone, write it in your own library".
   No proble, I put it in my libraray. Here is the code. Please note, it is
perfectly compatible with current urllib.urlencode:

# obj must be either dict or list of tuples [(k1, v1), (k2, v2), ...] or list of lists [[k1, v1], [k2, v2], ...]
def urlencode(obj):
     l = []
     if type(obj) == type({}):
         obj = obj.items()

     for k, v in obj:
         k = quote_plus(str(k))
         v = quote_plus(str(v))
         l.append(k + '=' + v)

     return string.join(l, '&')

Oleg.
----
     Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
           Programmers don't die, they just GOSUB without RETURN.





More information about the Python-list mailing list