urldecode function?

Fredrik Lundh fredrik at pythonware.com
Thu Aug 14 12:45:17 EDT 2008


rkmr.em at gmail.com wrote:

> is there a function that does the opposite of urllib.urlencode?
> 
> for example
> urldecode('Cat=1&by=down&start=1827')
> 
> returns a dictionary with {'Cat':1, 'by':'down','start':1827)

the cgi modules contains assorted stuff for parsing serialized HTTP 
forms and query strings.  here's a quick way to get a dictionary:

 >>> import cgi
 >>> dict(cgi.parse_qsl("Cat=1&by=down&start=1827"))
{'start': '1827', 'by': 'down', 'Cat': '1'}

there's also:

 >>> cgi.parse_qs("Cat=1&by=down&start=1827")
{'start': ['1827'], 'by': ['down'], 'Cat': ['1']}
 >>> cgi.parse_qsl("Cat=1&by=down&start=1827")
[('Cat', '1'), ('by', 'down'), ('start', '1827')]

(both these forms handle multiple instances of the same key)

to autoconvert things that look like integers, you can do e.g.

 >>> def safeint(x):
...     try:
...             return int(x)
...     except ValueError:
...             return x # leave as is
...
 >>> dict((k, safeint(v)) for k, v in
     cgi.parse_qsl("Cat=1&by=down&start=1827"))
{'start': 1827, 'by': 'down', 'Cat': 1}

</F>




More information about the Python-list mailing list