Entry
New urlencode (was: urllib.urlencode small improvement)
Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 260, Skip Montanaro
"""
Packages: networking.internet
"""
"""
> Currently urllib.urlencode takes dictionary {"x": "y", "u": "v"}
> and produces encoded string as "x=y&u=v". But wat if I want to
> repeat some keys: "x=y1&x=y2&u=v"? I cannot pass this to urlencode
> using dictionaries!
Why not modify urlencode to explode dict values into multiple instances if
the value was a list or tuple instead? Example:
{"x": ["y1", "y2], "u": "v"} ---> x=y1&x=y2&u=v
The resulting urlencode would look something like the following lightly
tested code:
"""
from urllib import quote_plus # added by PSST
def urlencode(obj):
l = []
for k, v in obj.items():
k = quote_plus(k)
if type(v) is types.StringType: v = [v]
for i in v:
l.append("%s=%s" % (k, quote_plus(i)))
return string.join(l, "&")