Python dict.get returns 0 evaluated as false

Viewed 414

I use dict.get() in conditional statements to check if something exists in user-defined dictionaries (typically coming from yaml or json config files). This has worked pretty well for me, but I have this edge case:

my_dict = {
    'my_key': 0.0
}

if my_dict.get('my_key'):
    # do some stuff

Here, 'my_key' does exist in the dictionary, so get will not return None. However, because 0.0 is treated as False in conditionals, this does not work the way that it does in most cases. I can fix with this:

if my_dict.get('my_key') is not None:
    # do some stuff

but this seems a bit verbose to me. For one conditional, it's not a big deal, but stringing together multiple conditionals can quickly become a little annoying.

My question is simply: is there a less verbose way to do this?

1 Answers

No, there's no less verbose to do it with .get(). All zero-valued numbers, empty sequences or None will be evaluated to False. If you want to differentiate between them, you'll have to explicitly check for None.

But as @mingaleg mentioned in the comments. If you're only using it to check if the key is in the dictionary, you could use if 'my_key' in my_dict:

Related