How do I test a dictionary for a specific key?

This is a question for one of my practice questions but I do not even know how to begin this let alone complete it. I am very new to Python still and learning.

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: 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!

Read more here:

Content Attribution

This content was originally published by Mt Supra at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: