Programming from zero

Use a default when a config key is missing

easyDictionaries

Problem statement

A service config may or may not set a timeout. Given config = {"host": "api.internal", "retries": 3}, print the timeout, using 30 when the key is missing:

Timeout: 30

Examples

Example 1

Input: config = {"host": "api.internal", "retries": 3}

Output: Timeout: 30

Explanation: timeout is not in the dictionary, so the default 30 is used.

Hints

Approach

Optimal

Looking up a missing key with square brackets raises KeyError and stops the program. The .get() method is the safe alternative: config.get("timeout", 30) returns the stored value if the key exists, and 30 otherwise. Without a second argument, .get() returns None for a missing key. This is the standard way to support optional settings with sensible defaults.

Python
config = {"host": "api.internal", "retries": 3}
timeout = config.get("timeout", 30)
print(f"Timeout: {timeout}")

Follow-up questions

  • Check whether a key exists with if "timeout" in config: and print a different message for each case.

Frequently asked questions

Use [] for required settings, where a missing key is a real error you want to see immediately. Use .get() with a default for optional settings.