Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional key in dictionary - python [duplicate]

I have a function create_group with an optional parameter user_device=None. If a non-None value is provided for user_device, I want a dictionary targeting_spec to include the key-value pair "user_device": user_device, and if no non-None value is provided, I do not want targeting_spec to include this key-value pair.

How I do it now:

def create_group(..., user_device=None, ...):
    ...
    targeting_spec = {
        ...
    }
    if user_device:
        targeting_spec["user_device"] = user_device
    ...

Is this an accepted way of doing this? If not, what is? I ask because this seems like the type of thing Python would love to solve elegantly.

like image 379
tscizzle Avatar asked Jul 11 '14 17:07

tscizzle


1 Answers

Your approach is fine, provided you don't need to support empty values.

Consider passing in user_device=0, for example. user_device is not None, but it is a falsey value.

If you need to support falsey values apart from None, use is not None to test:

if user_device is not None:
    parameters["user_device"] = user_device
like image 190
Martijn Pieters Avatar answered Sep 29 '22 13:09

Martijn Pieters