Check if a Key Exists in a Dictionary in Python
In Python, you can check if a key exists in a dictionary using the in
keyword.
For example:
my_dict = {'name': 'James', 'age': 35, 'city': 'Toronto'}
if 'city' in my_dict:
print("Key 'city' exists in the dictionary")
else:
print("Key 'city' doesn't exist in the dictionary")
Output:
Key 'city' exists in the dictionary
Check if a key doesn’t exist in a dictionary
You can check if a key doesn’t exist in a dictionary using the not in
keyword.
For example:
my_dict = {'name': 'James', 'age': 35, 'city': 'Toronto'}
if 'occupation' not in my_dict:
print("Key 'occupation' doesn't exist in the dictionary")
else:
print("Key 'occupation' exists in the dictionary")
Output:
Key 'occupation' doesn't exist in the dictionary