5 Ways to Determine if a Key is Present in a Dictionary
Here are five examples demonstrating how to check if a key exists in a dictionary:
- Using the
in
keyword:
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}
if 'apple' in my_dict:
print("The key 'apple' exists in the dictionary.")
else:
print("The key 'apple' does not exist in the dictionary.")
- Using the
get()
method:
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}
if my_dict.get('apple') is not None:
print("The key 'apple' exists in the dictionary.")
else:
print("The key 'apple' does not exist in the dictionary.")
- Using exception handling (try-except):
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}
try:
value = my_dict['apple']
print("The key 'apple' exists in the dictionary.")
except KeyError:
print("The key 'apple' does not exist in the dictionary.")
- Using the
keys()
method:
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}
if 'apple' in my_dict.keys():
print("The key 'apple' exists in the dictionary.")
else:
print("The key 'apple' does not exist in the dictionary.")
- Using the
in
operator with a for loop:
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}
for key in my_dict:
if key == 'apple':
print("The key 'apple' exists in the dictionary.")
break
else:
print("The key 'apple' does not exist in the dictionary.")
All these examples achieve the same result of checking if the key 'apple'
exists in the dictionary my_dict
.