Skip to content
Advertisement

Only add to a dict if a condition is met

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.

JavaScript

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):

JavaScript

I hope this was clear enough, does anyone know how to solve this?

Advertisement

Answer

You’ll have to add the key separately, after the creating the initial dict:

JavaScript

Python has no syntax to define a key as conditional; you could use a dict comprehension if you already had everything in a sequence:

JavaScript

but that’s not very readable.

If you are using Python 3.9 or newer, you could use the new dict merging operator support and a conditional expression:

JavaScript

but I find readability suffers, and so would probably still use a separate if expression:

JavaScript

Another option is to use dictionary unpacking, but for a single key that’s not all that more readable:

JavaScript

I personally would never use this, it’s too hacky and is not nearly as explicit and clear as using a separate if statement. As the Zen of Python states: Readability counts.

Advertisement