def key_exists(dictionary, key):
if key in dictionary:
return True
else:
return False
student = {"name": "John", "age": 20, "grade": "A"}
key_to_check = "age"
if key_exists(student, key_to_check):
print(f"The key '{key_to_check}' exists in the dictionary.")
else:
print(f"The key '{key_to_check}' does not exist in the dictionary.")
Code Explanation:
Define the Function:
def key_exists(dictionary, key):
The function key_exists() takes two parameters:
dictionary: The dictionary in which to search for the key.
key: The key to check for.
Check for Key Presence:
if key in dictionary:
The in keyword is used to check if the key exists in the dictionary.
Return the Result:
return True
If the key exists, the function returns True, otherwise it returns False.
Example Dictionary:
student = {"name": "John", "age": 20, "grade": "A"}
A sample dictionary student is defined.
Specify Key to Check:
key_to_check = "age"
The variable key_to_check is assigned the value "age".
Call the Function and Print Result:
if key_exists(student, key_to_check):
The function is called to check if "age" exists in the student dictionary.
The output will be:
The key 'age' exists in the dictionary.
0 Comments:
Post a Comment