2

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?

KindaTechy
  • 1,041
  • 9
  • 25
  • 4
    `if 'my_key' in my_dict:` – mingaleg Mar 12 '20 at 17:41
  • Look at Truthy and Falsy values in python for better understanding. – Ch3steR Mar 12 '20 at 17:42
  • I think you're stuck with it. Depending on what you are doing in the conditional (and in this case you are pulling configuration) sometimes having a default is sufficent: `my_key = dict.get("my_key", 1.0)` - removing the need for the conditional completely. – tdelaney Mar 12 '20 at 17:48
  • The closing is right. As it relates to my intended use, I just need 'my_key' in my_dict, which is answered in the linked post. I searched SO for it, but didn't use the right language so I didn't find it. Thanks everyone for the time and attention to this! – KindaTechy Mar 12 '20 at 17:51
  • 1
    @kederrac It's similar, but I think it's a gray area. I'd personally say it isn't a strict duplicate as the question is more about the problem of truthy values. However, since the answers to the other question also answer this one, it could be seen as a duplicate. – Ted Klein Bergman Mar 12 '20 at 17:52

1 Answers1

3

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:

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50