views:

585

answers:

2

I am trying to convert a Python dictionary to a string for use as URL parameters. I am sure that there is a better, more Pythonic way of doing this. What is it?

x = ""
for key, val in {'a':'A', 'b':'B'}.items():
    x += "%s=%s&" %(key,val)
x = x[:-1]
+13  A: 

Use urllib.urlencode(). It takes a dictionary of key-value pairs, and converts it into a form suitable for a URL (e.g., key1=val1&key2=val2).

mipadi
Reference: http://docs.python.org/library/urllib.html#urllib.urlencode
S.Lott
A: 

What you have done is quite ok.

Maybe you can directly use a list comprehension, and use the join method to regroup the terms, separated by a & (no need to remove the last character).

dico = {'a':'A', 'b':'B'}
x = "&".join( "%s=%s"%item for item in dico.items() )

EDIT: the urllib.urlencode will also ensure that are converted in ASCII, that is not done, here. But this is the home-made pythonic way to do it ;-) (no extra library required)

EDIT2: since the question was "how to write this code in a more pythonic way", I believe that my answer is still correct (only one simple list comprehension). Of course, since the urllib.urlencode is doing it, with correct encoding, it's better to use it.

ThibThib
It's not at all pythonic to rewrite a function that the standard library provides.
Triptych
it's not OK: you need to escape key and val. URL encoding is surprisingly subtle, best to use the library function.
Nelson
`urllib` is included in the Python standard library, so it's not _really_ an "extra library".
mipadi