Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Return a default when a key is missing

Create a helper that extracts values from mappings or sequences and returns a fallback when the key/index is missing or the container is invalid.

Python practice9 minError Handling & Edge CasesBeginnerLast updated March 20, 2026

Problem statement

Accessing values can raise exceptions if the key or index is missing, or if the container is None or not subscriptable. Implement get_with_default(container, key, default) that: - Returns container[key] when the access succeeds. - If accessing container[key] raises KeyError, IndexError, or TypeError, return default instead. - Be tolerant of common container types such as dicts and lists. This function helps call sites remain robust when inputs are unpredictable.

Task

Implement get_with_default(container, key, default) that safely returns container[key] when available, otherwise returns default without raising errors.

Examples

Missing dict key

Input

get_with_default({'a': 1}, 'b', 0)

Output

0

Key 'b' is not in the dict, so default 0 is returned.

Input format

Three values: container (e.g., dict or list), key (any hashable or integer index), default (any).

Output format

The value from container[key] or the default if not accessible.

Constraints

Do not raise when the container is None or the key/index is missing; return the default instead.

Samples

Sample 1

Input

get_with_default([10, 20], 1, 0)

Output

20

Index 1 exists in the list and returns 20.