Problem No 2
Get a value from a dictionary with a default
Easy≈ 9 minute session
Lesson guide
What this Python exercise practices
Get a value from a dictionary with a default is a beginner practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 9 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Beginner
- Estimated time
- 9 minutes
Practice path
Summary
Retrieve a value for a key from a dictionary, returning a provided default when missing.
Problem statement
Write a function get_with_default(dct, key, default) that returns the value associated with key in dct if it exists (even if that value is None). If key is not present in dct, return default. Do not modify the input dictionary.
Task
Implement a helper that returns dct[key] if present, otherwise returns a default value. If the stored value is None, return None (not the default).
Examples
Key present
Input
get_with_default({'a': 1, 'b': 2}, 'b', 0)
Output
2
Explanation
Key 'b' exists, so its value 2 is returned.
Input format
A Python expression calling get_with_default(dict, key, default)
Output format
Return the value from the dictionary or the default. The test harness compares str(return_value) (or '' if None).
Constraints
- dct may be empty - Keys and values are general Python objects - Do not print; return the value
Samples
Sample input 0
get_with_default({'name': 'Sam'}, 'age', 'unknown')
Sample output 0
unknown
Explanation 0
Key 'age' missing so default 'unknown' is returned.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.