Python Check if a Specific Key Exists in a Dictionary
In Python, you can useinkeyword to check whether a specific key exists in a dictionary. This method is very efficient because it utilizes the hash table feature of dictionaries.
Example
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
key_to_find = 'age'
if key_to_find in my_dict:
print(f"The key '{key_to_find}' exists in the dictionary.")
else:
print(f"The key '{key_to_find}' does not exist in the dictionary.")
key_to_find = 'age'
if key_to_find in my_dict:
print(f"The key '{key_to_find}' exists in the dictionary.")
else:
print(f"The key '{key_to_find}' does not exist in the dictionary.")
Code analysis:
my_dictis a dictionary containing three key-value pairs.key_to_findis the key we want to look up.if key_to_find in my_dict:This line of code usesinkeyword to checkkey_to_findwhether it exists inmy_dictthe keys of- If the key exists, the program prints a message that the key exists; if it does not exist, it prints a message that the key does not exist.
Output result:
The key 'age' exists in the dictionary.Other Extensions
Python3 Examples