I am using urllib.urlencode
to build web POST parameters, however there are a few values I only want to be added if a value other than None
exists
You can deal with all optional items using a single condition by using a dictionary comprehension:
apple = "red"
orange = None
dictparams = {
key: value for key, value in
{
"apple": apple,
"orange": orange
}.items()
if value is not None
}
The dictparams
result will not contain "orange"
in this case, because orange
is None
:
{'apple': 'green'}