0

This is a question for one of my practice questions but I do not even know how to begin this let alone complete it.

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: Try to access the value in the dictionary at the given key (wrap this in a try-except statement) If the access is successful, just return the value 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!

  • Have a look here for inspiration: https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary Checks whether a key exists in the dicitionary and then you can access it. – Ivo De Jong Feb 19 '21 at 07:28
  • Does this answer your question? [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – Krishna Chaurasia Feb 19 '21 at 07:29

0 Answers0