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 for them.
apple = 'green'
orange = 'orange'
params = urllib.urlencode({
'apple': apple,
'orange': orange
})
That works fine, however if I make the orange
variable optional, how can I prevent it from being added to the parameters? Something like this (pseudocode):
apple = 'green'
orange = None
params = urllib.urlencode({
'apple': apple,
if orange: 'orange': orange
})
I hope this was clear enough, does anyone know how to solve this?
To piggyback on sqreept's answer, here's a subclass of
dict
that behaves as desired:This will allow values of existing keys to be changed to
None
, but assigningNone
to a key that does not exist is a no-op. If you wanted setting an item toNone
to remove it from the dictionary if it already exists, you could do this:Values of
None
can get in if you pass them in during construction. If you want to avoid that, add an__init__
method to filter them out:You could also make it generic by writing it so you can pass in the desired condition when creating the dictionary:
You can clear None after the assignment:
Pretty old question but here is an alternative using the fact that updating a dict with an empty dict does nothing.
Another valid answer is that you can create you own dict-like container that doesn't store None values.
yields:
You'll have to add the key separately, after the creating the initial
dict
:Python has no syntax to define a key as conditional; you could use a dict comprehension if you already had everything in a sequence:
but that's not very readable.
I did this. Hope this help.
Expected output :
{'orange': 10, 'apple': 23}
Although, if
orange = None
, then there will be a single entry forNone:None
. For example consider this :Expected Output :
{None: None, 'apple': 23}