Python
dict
has_key
in-operator
programming-tips

Should I use 'has_key' or 'in' on Python dicts?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In the world of Python programming, developers often encounter scenarios where they need to check the existence of a key in a dictionary. Historically, Python provided a method named has_key() for this purpose. However, with more recent versions of Python (specifically from Python 3 onwards), the usage of has_key() is discouraged and has been removed. Instead, the recommended and idiomatic way to check if a key exists in a dictionary is to use the in keyword. This article explores the differences, the reasons behind the deprecation, and offers guidance on using in effectively.

Historical Perspective

has_key() Method

The has_key() method was available in Python 2 and was used as follows:

python
1my_dict = {'a': 1, 'b': 2}
2# Check if 'a' is a key in my_dict
3if my_dict.has_key('a'):
4    print("Key 'a' exists in the dictionary.")

This method returns True if the specified key is present in the dictionary, and False otherwise.

in Keyword

The in keyword provides a more readable and versatile way to perform the same check. Introduced as an alternative to has_key(), it works like this:

python
1my_dict = {'a': 1, 'b': 2}
2# Check if 'a' is a key in my_dict
3if 'a' in my_dict:
4    print("Key 'a' exists in the dictionary.")

Why has_key() Was Removed

  1. Readability and Pythonic Style: Python promotes readability and a particular style of coding, often referred to as "Pythonic". The in keyword fits this philosophy better by being more versatile and readable.
  2. Consistency Across Collections: The in keyword is consistent across all Python collections. It can be used with lists, tuples, sets, and dictionaries, making the language easier to learn and use.
  3. Simplicity: By removing has_key(), the language maintains simplicity with fewer methods to remember for common operations.
  4. Maintenance and Future-proofing: Removing older, redundant methods helps in maintaining the language and its libraries efficiently. It also sets a clear pathway towards Python 3 and beyond.

Using in with Python Dicts: Examples

Here's how you can effectively harness the power of the in keyword when working with dictionaries:

Basic Key Existence Check

python
1my_dict = {'x': 10, 'y': 20}
2
3# Check if 'x' is in my_dict
4if 'x' in my_dict:
5    print("Key 'x' found.")
6else:
7    print("Key 'x' not found.")

Iterating and Checking Multiple Keys

python
1keys_to_check = ['x', 'y', 'z']
2my_dict = {'x': 10, 'y': 20}
3
4for key in keys_to_check:
5    if key in my_dict:
6        print(f"Found key: {key}")
7    else:
8        print(f"Key not found: {key}")

Use Case in Functions

The in keyword can also cleanly handle conditions inside functions:

python
1def check_key_existence(dictionary, key):
2    return key in dictionary
3
4my_dict = {'apple': 3, 'banana': 2}
5# Checking if 'apple' exists
6exists = check_key_existence(my_dict, 'apple')
7print(f"Does 'apple' exist? {exists}")

Comparison Table

Feature/Aspecthas_key()in Keyword
Syntaxdict.has_key(key)key in dict
AvailabilityPython 2Python 2 and 3
ReadabilityLess readableMore readable
ConsistencyLimited to dictionariesWorks with all collections (lists, sets, tuples)
Current StatusRemoved in Python 3Standard practice

Conclusion

For developers working with Python 3, the in keyword is the recommended and idiomatic way to check for the existence of keys in dictionaries. For those transitioning from Python 2, updating legacy code from has_key() to in is a crucial step for compatibility and modern style. Utilizing in not only aligns with best practices but also ensures cleaner, more efficient, and easier-to-read code. As Python continues to evolve, embracing these changes is essential for keeping projects robust and maintainable.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.