Given:
>>> d = {'a': 1, 'b': 2}
Which of the following is the best way to check if 'a'
is in d
?
>>> 'a' in d
True
>>> d.has_key('a')
True
Answers
The best and preferred way to check if 'a'
is in d
is:
'a' in d
This is the modern, Pythonic approach and works in all versions of Python (both Python 2 and Python 3). It checks whether 'a'
is a key in the dictionary d
and returns True
if the key exists, and False
otherwise.
On the other hand:
d.has_key('a')
is deprecated and was removed in Python 3. It only exists in Python 2, so you should avoid using it.
Summary:
- Use
'a' in d
: ✅ Preferred and works in all modern Python versions. d.has_key('a')
: ❌ Deprecated and removed in Python 3.