In this article, we will discuss the different methods on how to check if a key already exists in a dictionary or not.
Table of Contents
Using the in
keyword
The in
keyword as the name suggests can be used to check if a value is present in some data structure or not. Using this keyword, we can check whether a given key is present in a dictionary or not.
For example,
1 2 3 4 5 6 7 |
d = {"a": 10, "b": 2, 'c': 4} if "d" in d: print("Key exists") else: print("Key does not exist") |
Output:
In the above example, we directly search the key in the dictionary. If the key is found then the if
statement returns True otherwise it returns False. This is probably the best and the fastest way to achieve this. Since we are directly searching the dictionary, it uses dictionary hashing and not linear search.
We can also use the keys()
function with the in keyword. This function returns a view-type object of all the keys in the dictionary. If we use the in
keyword here, it will do a linear search so the time taken will increase if we are dealing with a large dictionary.
We use this in the following example.
1 2 3 4 5 6 7 |
d = {"a": 10, "b": 2, 'c': 4} if "d" in d.keys(): print("Key exists") else: print("Key does not exist") |
Output:
Using the get()
function
The get()
function is associated with dictionaries in Python. We can return the value associated with a key in a dictionary. We can use it to check whether a key exists or not.
See the code below.
1 2 3 4 5 |
d = {"a": 10, "b": 2, 'c': 4} if d.get('d') == None: print("Key Does Not Exist") |
Output:
Here we worked on a simple logic that if the key already exists in the dictionary, then it must return some value. So if None is being returned then the given key must not exist in the dictionary.
Further reading:
Using the has_key()
function
This method is by far the most direct approach to our problem. This function returns True if the given key exists in a dictionary otherwise, it returns False.
For example,
1 2 3 4 |
d = {"a": 10, "b": 2, 'c': 4} print(d.has_key('d')) |
Output:
However, this function was deprecated in Python 3 so it only works for Python 2 users. Therefore, its use should be avoided.
Using the try
and except
block
In Python, whenever we encounter an error an exception is raised and the program stops. So if we try to use the value from a dictionary whose key does not exist then a KeyError is raised.
Python has a very convenient way to deal with exceptions. If we have any code, which we feel suspicious about and which may raise an exception, then we can put it in a try
block. We use an except
block with this. The except
block catches an exception raised in the try
block and executes some other block of code. If an exception is raised, the code in except
block gets executed so the program does not stop.
We can use this method to check if a key exists in a dictionary or not.
For example,
1 2 3 4 5 6 7 |
d = {"a": 10, "b": 2, 'c': 4} try: sample = d["d"] #we try to get the value of key we wish to check except KeyError: print("Does not exist") |
Output:
Using the setdefault()
function
This functions is discussed here just for some additional information. Basically, it is used to assign a key-value pair in a dictionary if the given key does not exist. It does not override the value if the key is already present in the dictionary.
For example,
1 2 3 4 5 |
d = {"a": 10, "b": 2, 'c': 4} d.setdefault('d',5) print(d) |
Output:
As you can see, since the key did not exist, it added the key with some specified value. On comparing its length with the original dictionary we can find out whether the key existed or not.
For example,
1 2 3 4 5 6 7 8 |
d = {"a": 10, "b": 2, 'c': 4} a = len(d) d.setdefault('d',5) b = len(d) if a!=b: print("Key did not exist earlier but was added") |
Output:
Source:
https://docs.python.org/3/tutorial/datastructures.html
https://www.code2master.com/python/check-key-exists-dictionary-python/
That’s all about how to check if key exists in dictionary.