Open In App

Dictionary has_key() – Python

Last Updated : 17 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The has_key() method in Python was used to check whether a specified key exists in a dictionary. However, this method was removed in Python 3 and the preferred approach to check for a key’s existence is by using the in keyword. In Python 2.7, the has_key() method was commonly used, like so:

Python
d = {1: 'Welcome', 2: 'To', 3: 'Geeks'}

print(d.has_key(1))
print(d.has_key('To'))

Output
True
False

Explanation: d.has_key(1) returns True because key 1 exists. d.has_key(‘To’) returns False since ‘To’ is a value, not a key.

But if you’re using Python 3.x, you must replace has_key() with the in operator as shown earlier:

Python
d = {'a': 1, 'b': 2}
if 'a' in d:
   print("Yes")

Output
Yes

Explanation: ‘a’ in d returns True because ‘a’ is a key in the dictionary d. So the condition is satisfied and “Yes” is printed.

Syntax of has_key()

dict.has_key(key)

Parameter: key is the key you want to check in the dictionary.

Returns: True if the key is found, False otherwise.

Example of checking for a key in Python 3

Python
d = {"name": "Alice", "age": 30, "city": "New York"}

if "age" in d:
    print("Yes")
else:
    print("No")

Output
Yes

Explanation: In the updated Python 3 version, the in keyword is used to check if the key ‘age’ is present in the dictionary. It works much more efficiently and is easier to understand than the deprecated has_key() method.

Why has_key() was removed ?

has_key() method was removed from Python to make the language cleaner and more consistent. Instead, we now use the in keyword, which is easier to read and works not just with dictionaries but with other types of collections too. It fits better with Python’s goal of keeping code simple and readable. So, rather than writing something like my_dict.has_key(‘name’), we just write ‘name’ in my_dict’, which is shorter and more natural.

Advantages of using in keyword over has_key()

Understanding the advantages of using the in keyword over the deprecated has_key() method is important for several reasons:

  • Cleaner Code: in makes code simpler and easier to read.
  • More Flexible: Works with all types of collections, not just dictionaries.
  • Pythonic Style: Follows Python’s focus on simplicity and clarity.

Alternative methods for checking key

Besides the in keyword, you can also check if a key exists using the get() method of dictionaries.

Python
d = {1: 'Welcome', 2: 'To', 3: 'Geeks'}

if d.get(1) is not None:  # Use integer 1, not string "1"
    print("Yes")
else:
    print("No")

Output
Yes

Explanation: This condition checks if key 1 exists in the dictionary by ensuring the returned value isn’t None. Since key 1 is present, the condition is True and “Yes” is printed. This approach avoids a KeyError that could occur with direct access like d[1] if the key didn’t exist.



Next Article

Similar Reads