Should I use 'has_key()' or 'in' on Python dicts?
It is recommended to use the in
keyword to check if a key exists in a Python dict, rather than the has_key()
method. This is because the in
keyword is more readable and is consistent with the way we check for the existence of elements in other Python data types, such as lists and sets.
Here's an example of using the in
keyword:
my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'a' in my_dict:
print("'a' exists in my_dict")
else:
print("'a' does not exist in my_dict")
Note that has_key()
is deprecated on python 3.