Python 3 – dictionary has_key() Method
In Python 3, the has_key()
method has been removed from the dictionary object. However, there are other ways to check whether a key exists in a dictionary or not.
Using the in
keyword
The easiest way to check if a key exists in a dictionary is to use the in
keyword. This method is much faster and shorter than using the has_key()
method in Python 2.
# creating a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
# using the 'in' keyword to check if a key exists
if 'age' in my_dict:
print("Age exists in my_dict")
else:
print("Age does not exist in my_dict")
Output:
Age exists in my_dict
Using the get()
method
Another way to check if a key exists in a dictionary is to use the get()
method. This method returns the value for the specified key if it exists in the dictionary, otherwise it returns the default value (which is None
by default).
# creating a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
# using the 'get()' method to check if a key exists
if my_dict.get('age') is not None:
print("Age exists in my_dict")
else:
print("Age does not exist in my_dict")
Output:
Age exists in my_dict
Using exception handling
The third way of checking if a key exists in a dictionary is by using exception handling. This involves trying to access the key and catching the KeyError
if it does not exist.
# creating a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
# using exception handling to check if a key exists
try:
value = my_dict['age']
print("Age exists in my_dict")
except KeyError:
print("Age does not exist in my_dict")
Output:
Age exists in my_dict
Conclusion
The has_key()
method has been deprecated in Python 3, but there are many other ways to check if a key exists in a dictionary. One can use the in
keyword, the get()
method or even exception handling. It is important to choose the right method based on its performance, readability and suitability to the particular use case.