How to check if key exists in a python dictionary?In this python tutorial, we look at dictionaries and how to check if a key exists in a dictionary we also explain the code to facilitate further learning.
However, in case you are here only for the solution use this link.
Table of Contents
- Why do we check if a key exists in python dictionary
- Checking if a key exists using in operator
- Using the get() method
- Closing thoughts
- Other Related Concepts
If you are here to learn how to check if a key exists in a dictionary it is most likely because of two reasons, either you are new to python or you tried using the has_key methods and were served with an error. In case it is the latter, this is because python3 has removed the has_key methods. However, there are other equally efficient methods and we look at them below.
Why do we check if a key exists in python dictionary?Dictionaries are common and extensively used data types in python. They hold key-value pairs and these values are accessed by the respective keys in order to perform many tasks on them. And this is why it is a good practice to check if the key exists below you try to access its relevant value. Doing so would also reduce the likelihood of facing errors.
Now let's look at the different ways you can use to check if a key exists in python dictionary.
Checking if a key exists using in operators:The in operator in python is a membership operator, it takes two parameters and checks if one is a member of the other and returns a boolean True or False. In our case, we the in operator to check if the key is a member of the dictionary.
Code to check if a key exists in python dictionary
Now let's check for a negative case
Similarly, the not in operator can also be used. However, remember the in operator is case sensitive hence you could either ensure all your keys are in the same case or you could use the upper() or lower() methods respectively.
Using the get() methodThe get() method is a dict method that is used to return the value of the key passed as an argument and if the key is not present it returns either a default value (if passed) else it returns None. Using this method we can pass a key and check if a key exists in python dictionary.
Syntax of get()
Here dictionary is the name of the dict you indent to work with
ParametersKeyname - The keyname of the value to intent to return
value - Optional, this value is returned in case the key does not exist
Code to check if the key exists in a dictionary using get()
And for a negative case,
While using this method keep in mind that this would not be accurate in case you have a key with the value None in case you don't then this method would work fine.