Search code examples
pythonpython-3.xurllib

Python: Urllib keeps booleans capitalized when using urllib.parse.urlencode()


I have a dict of arguments I want urllib to parse, so I am using urllib.parse.urlencode(). However, when one of the arguments is a bool, it keeps the bool capitalized in the result, which doesn't work with what I'm trying to do.

>>> import urllib
>>> args = {'foo': True, 'bar': False}
>>> urllib.parse.urlencode(args)
'foo=True&bar=False'

Desired result: 'foo=true&bar=false'

What's the best way to resolve this? I could just fix it manually by looping through args and replacing each bool with a lowercase string but I feel like there's a better way that I'm not aware of.


Solution

  • There is no shortcut for this. As the urlencode method accepts a sequence of pairs (tuples), it is in theory more efficient to not rebuild a dictionary, but pass this list as argument:

    [(k, str(v).lower() if isinstance(v, bool) else v) for k, v in args.items()]