urllib.urlencode small improvement

Skip Montanaro skip at mojam.com
Thu Oct 28 11:21:20 EDT 1999


    Oleg> Currently urllib.urlencode takes dictionary {"x": "y", "u": "v"}
    Oleg> and produces encoded string as "x=y&u=v". But wat if I want to
    Oleg> repeat some keys: "x=y1&x=y2&u=v"? I cannot pass this to urlencode
    Oleg> 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:

    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, "&")




More information about the Python-list mailing list