Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Build a phonebook dictionaryE02. Get a value from a dictionary with a defaultE03. Add and remove dictionary entriesM

Problem No 2

Get a value from a dictionary with a default

Easy

9 minute session

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.

Code editor
Loading editor…

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.

02:09 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.