Alex Rivera | Logout

urlencode a multidimensional dictionary in python

Asked 2010-10-25T10:51:08.243
13

How can I get a URL-encoded version of a multidimensional dictionary in Python? Unfortunately, urllib.urlencode() only works in a single dimension. I would need a version capable of recursively encoding the dictionary.

For example, if I have the following dictionary:

{'a': 'b', 'c': {'d': 'e'}}

I want to obtain the following string:

a=b&c[d]=e
Edit
Report

1 Answer

3

Something like this?

a = {'a': 'b', 'c': {'d': 'e'}}

url = urllib.urlencode([('%s[%s]'%(k,v.keys()[0]), v.values()[0] ) if type(v)==dict else (k,v) for k,v in a.iteritems()])

url = 'a=b&c%5Bd%5D=e'
answered 2010-10-25T10:59:56.557

Your Answer