Question: In this part, you'll write a safe version of testing a dictionary for a specific key and extracting the corresponding element. Normally, if you try

 In this part, you'll write a safe version of testing a

In this part, you'll write a safe version of testing a dictionary for a specific key and extracting the corresponding element. Normally, if you try to access a key that does not exist, your program crashes with a keyError exception. Here, you'll write a function which: is named safe_access takes 3 arguments: a dictionary, a key, and a default return value returns 1 value the value in the dictionary for the given key, or the default return value The third argument to this function is a default argument, whose initial value should be the Python keyword None. Your task in this function is three-fold: 1. Try to access the value in the dictionary at the given key (wrap this in a try-except statement) 2. If the access is successful, just return the value 3. If the access is NOT successful (i.e. you caught a KeyError ), then return the default value instead You must include a try-except statement in your function! Graded vi Read Only safe_access({"one": [1, 2, 3], "two": [4, 5, 6], "three": "something"}, "three") assert v1 == "something" v2 Read Only safe_access({"one": [1, 2, 3], "two": [4, 5, 6], "three": "something"}, "two", [10, 11, 12]) assert set(v2) == set((4, 5, 6)) Read Only default_val = 3 try: value = safe_access({"one": 1, "two": 2}, "three", default_val) except: assert False else: assert value == default_val

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!