Sometimes we might need to check whether a key exists in the Python dictionary. In this article, we will discuss the fastest way to check a key that exists in a Python dictionary.
The has_key() method was removed in Python 3 . So the recommended way is to use the in operator.
Two ways to check whether a key exists in a dictionary.
- Checking the key in the dictionary
- Checking the key in the dictionary keys list
The in operator
The in or not in operator in Python checks the membership. The x in s evaluates to true if x is a member of s and false otherwise.
Syntax
x in s
x not in s
To check whether a key exists in a dictionary:
user = {"name": "Tom","age" : "24"}
# check name exists in user method 1
if "name" in user:
print("Name key exits in user")
# check name exists in users method 2
if "name" in user.keys():
print("Name key exits in user")
Output
Name key exits in user
Name key exits in user
So both methods check the membership of a key, but the question is which method is fastest? Let’s find out.
Check using the in operator and dictionary.
import time
user = {"name": "Tom","age" : "24"}
start = time.time()
for x in range(10000000):
has_name = "name" in user
stop = time.time()
print(f"Elapsed time: {round(stop-start,4)} sec")
Output
Elapsed time: 0.9452 sec
Check using the in operator and dictionary keys list.
import time
user = {"name": "Tom","age" : "24"}
start = time.time()
for x in range(10000000):
has_name = "name" in user.keys()
stop = time.time()
print(f"Elapsed time: {round(stop-start,4)} sec")
Output
Elapsed time: 1.6135 sec
We can see that user.keys() method is slower compared to the “name” in user.
As per the time complexity document, the time complexity of in operator as follows:
- dict – O(1), which means it will take constant time does not depend on the size of data.
- list – O(n), proportional to the amount of data.
Elapsed time of operation:
- dict – “name” in user – 0.942 sec
- list – “name” in user.keys() – 1.613 sec
Conclusion
In conclusion, the fastest way to check a key in a Python dictionary is to use the in operator and dictionary ( key in dict
). Read about how to find substring in a Python string.