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.")
#source code --> clcoding.com
Code Explanation:
Define the Function
def key_exists(dictionary, key):
dictionary → This parameter represents the dictionary we want to check.
key → This is the key we are checking for inside the dictionary.
Check if the Key Exists
if key in dictionary:
return True
else:
return False
The in keyword checks if the given key exists inside the dictionary.
If the key is found, the function returns True.
If the key is not found, it returns False.
Example Usage
student = {"name": "John", "age": 20, "grade": "A"}
key_to_check = "age"
We create a dictionary called student.
We store "age" in key_to_check (this is the key we want to check).
Calling the Function
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.")
The function key_exists(student, key_to_check) is called.
If "age" exists in student, it prints:
The key 'age' exists in the dictionary.
If "age" was not in the dictionary, it would print:
The key 'age' does not exist in the dictionary.
0 Comments:
Post a Comment