Coding Quiz - Safely Extract Values from a Dictionary
In this coding quiz, you will write a function to safely extract values for specific keys from a dictionary
.
When a user selects a key from the given dictionary, the function should return the corresponding value or return a user-defined default value if the key does not exist.
Use the dictionary get method to safely extract values for specific keys.
def solution(dictionary, key, default_value): # Write your code here return
Constraints
-
The inputs are a dictionary, a key, and a default value.
-
The dictionary keys are in string format.
-
The default value is specified at the time of the function call and should be returned if the key does not exist.
Example Input and Output
-
Input: Dictionary:
{"name": "John", "age": 30}
, Key:"occupation"
, Default Value:"Unregistered"
-
Output:
"Unregistered"
Safely Extract Values from a Dictionary
Safely extract and print the value for a given key from the dictionary. If the key does not exist, return the default value. For example, if the key does not exist, the output should be Not Registered
.
def get_value(d, k, default):
return d.get(k,
)
d = {"name": "John Doe", "age": 30}
print(get_value(d, "job", "Not Registered"))
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help