-1

I've been using the following syntax in my code for checking the existence of a key:

if dict.get("key") is not None:
    print "key found"

However, I have seen in other people's code the following syntax:

if 'key' in dict:
   print "key found"

I was just wondering which way is best to express a dictionary key null check and if there is an advantage (if any) to using one over the other.

I saw the existing question addressing the similar question of what are the alternatives to using .get() but just want to know if there is any advantage between the two examples I provided.

Community
  • 1
  • 1
Willem van Ketwich
  • 4,279
  • 7
  • 43
  • 51

3 Answers3

1

If there is a key entry with the value None the two expressions will return different results:

>>> d = {'key': None}
>>> d.get("key") is not None
False
>>> 'key' in d
True

If you want to check whether the key exists in the dictionary, the in operator should be used; it also makes your intention clearer. Additionally, it also works for other sequence types (eg. list, tuple, etc.)

BTW, don't use dict as a variable name; it shadows the builtin function/type dict.

Braiam
  • 4,345
  • 11
  • 47
  • 69
falsetru
  • 314,667
  • 49
  • 610
  • 551
1

This is better.

if 'key' in dict:
   print "key found"

Also, as @falsetrue noted, if you have a None value in your dict, if d.get('key') is not None becomes False which may not be the intended behaviour.

dict.get is useful when you use the value in an expression and want a default value to be used when the key is not in the dict.

d['key'] = 4
a = 5 + d.get('key', 0) # returns 0 if `key` is not in `d`
letmutx
  • 1,356
  • 11
  • 22
1

These two ways is different.

dict.get("key") is not None means dict has "key" and dict["key"] is not None.

"key" in dict means dict has "key" and don't care it's value is None or other.

gzc
  • 6,154
  • 5
  • 32
  • 59
  • 1
    What I explain is `dict.get("key") is not None` rather than a single `dict.get("key")`. – gzc Apr 01 '17 at 09:41