Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Select specific keys from a dictionary

Return a new dictionary containing only given keys from the source, inserting a default for missing keys.

Python practice10 minList & Dictionary PatternsBeginnerLast updated March 20, 2026

Problem statement

Implement select_keys(d, keys, default=None) which takes: - d: a dictionary - keys: an iterable (like list or tuple) of keys to select - default: value to use when a requested key is not present in d (default None) Return a new dictionary that contains each key from keys (in that order) mapped to either d[key] if present or default if missing. If keys contains duplicates, the resulting dictionary should contain the key once (its position should reflect the first occurrence in keys). Implement: select_keys(d, keys, default=None) -> dict

Task

Build a helper that extracts a subset of keys from a dictionary in a predictable order and fills missing keys with a default value.

Examples

select present keys

Input

select_keys({'a': 1, 'b': 2, 'c': 3}, ['b', 'c'])

Output

{'b': 2, 'c': 3}

Only 'b' and 'c' are selected and included in that order.

Input format

A dictionary d, an iterable of keys, and an optional default value.

Output format

A dictionary containing requested keys mapped to their values or default.

Constraints

Do not modify the original dictionary. Preserve the order of keys based on the order provided in keys.

Samples

Sample 1

Input

select_keys({'a': 1}, ['a', 'b'], default=None)

Output

{'a': 1, 'b': None}

Missing 'b' is included with default None.