In this article we will discuss how to check if a key exists in dictionary.

Suppose we have a dictionary of string and int i.e.

Now let’s check if key ‘test’ is present in dictionary or not.

Check if key exists in dictionary using in operator

Output:

check if key exists in dictionary using get()

Dictionary provides a method get() that accepts a key and default value.

  • If given key exists in dictionary then it returns its value,
  • If given key does not exists in dictionary then it returns the passed default value argument.
  • If given key does not exists in dictionary and Default value is also not passed in get() function, then get() function will return None.

Let’s use get() this to check if given key exists in dictionary,

As ‘test’ key exists in the dictionary and its value is not None, so output is,

But what if we are call dict.get() with key that exists in the dictionary with value ‘None’ i.e.

Adding key “from” in dict with value None

Now wordFreqDic.get(“from”) will return None.

So, we can not be always sure with the result of dict.get() that key exists in dictionary. Therefore, we should use dict.get() to check existence of key in dictionary only in scenarios when we are sure that there can not be an entry of key with given default value.

For example, above dictionary contains occurrence count of given words in an article, so value of keys should always be 0 or more.
So in this scenario, to check if the given key exists in dictionary we should pass -1 as default value in dict.get() i.e.

Output:

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.