Checking Key Existence in a Dictionary
You can check whether a specific key exists in a dictionary by using the in
keyword.
How to Use the in Keyword
The in
keyword returns True
or False
depending on whether the specified key exists in the dictionary.
Example of using the in keyword
my_dict = {'name': 'CodeFriends', 'age': 30}
# Check if a key exists in the dictionary
key_name = 'name' in my_dict
# Output: True
print(key_name)
key_address = 'address' in my_dict
# Output: False
print(key_address)
The in
keyword is useful for performing operations based on conditions or handling exceptions depending on key existence.
Example of using the in keyword
my_dict = {'name': 'CodeFriends', 'age': 30}
if 'email' in my_dict:
print("Email address exists.")
else:
print("Email address does not exist.")
Please note that the in
keyword only checks for the existence of keys in the dictionary and cannot verify the presence of a value
.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.