Only add to a dict if a condition is met

user1814016 picture user1814016 · Jan 10, 2013 · Viewed 55.9k times · Source

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?

Answer

Martijn Pieters picture Martijn Pieters · Jan 10, 2013

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

params = {'apple': apple}
if orange is not None:
    params['orange'] = orange
params = urllib.urlencode(params)

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

params = urllib.urlencode({k: v for k, v in (('orange', orange), ('apple', apple)) if v is not None})

but that's not very readable.

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

params = urllib.urlencode({
    'apple': apple,
    **({'orange': orange} if orange is not None else {})
})

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.