Check if a given key already exists in a dictionary
To check if a given key already exists in a dictionary, you can use the in
keyword. For example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'a' in my_dict:
print("Key 'a' exists in dictionary")
else:
print("Key 'a' does not exist in dictionary")
This will output Key 'a' exists in dictionary
. If you want to check if a key does not exist in the dictionary, you can use the not in
keyword.
For example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'd' not in my_dict:
print("Key 'd' does not exist in dictionary")
else:
print("Key 'd' exists in dictionary")
This will output Key 'd' does not exist in dictionary
.