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
I really like the neat trick in the answer here: https://stackoverflow.com/a/50311983/3124256
But, it has some pitfalls:
if
tests (repeated for key and value)None: None
entry in the resulting dict
To avoid this, you can do the following:
apple = 23
orange = None
banana = None
a = {
'apple' if apple else None: apple,
'orange' if orange else None : orange,
'banana' if banana else None: banana,
None: None,
}
del a[None]
Expected Output : {'apple': 23}
Note: the None: None
entry ensures two things:
None
key will always be present (del
won't throw an error)del
afterwards)If you aren't worried about these things, you can leave it out and wrap the del in a try...except
(or check if the None
key is present before del
ing). To address number 2 alternatively, you could also put the conditional check on the value (in addition to the key).