Write a function that receives a dictionary and a key, and returns the value for that key. Implement exception handling to return a custom message if the key is not found in the dictionary.
Example 1:
Input: dictionary = {"name": "Alice", "age": 25}, key = "name" Output: "Alice"
Example 2:
Input: dictionary = {"name": "Alice", "age": 25}, key = "address" Output: "Error: Key not found in the dictionary."
Use a try/except block to catch KeyError exceptions when trying to fetch a value from the dictionary.
def fetch_value(dictionary, key): try: return dictionary[key] except KeyError: return "Error: Key not found in the dictionary." print(fetch_value({"name": "Alice", "age": 25}, "name")) print(fetch_value({"name": "Alice", "age": 25}, "address"))
Unlock AI & Data Science treasures. Log in!