Skip to main content
Programming from zero

Use a default when a config key is missing

easyDictionaries

Problem statement

Real config files often leave settings out. If your program asks for a key that is not there, it should fall back to a sensible default instead of crashing. Every language has a way to say "give me this key's value, or this default if the key is missing."

Common mistake: reading a key that might be missing with plain lookup.

TEXT
Wrong: timeout = config["timeout"]

If "timeout" is not in the dictionary, Python stops with a KeyError and the whole program crashes. Using a lookup that accepts a default avoids that.

Your task: given config = {"host": "api.internal", "port": "8443"}, which has no "timeout" key, read the timeout with a default of "30", then print it in the form Timeout: <value>.

Expected output:

TEXT
Timeout: 30

Approach

Ask for the key, and give the fallback at the same time:

  • Python: config.get("timeout", "30"), where the second value is the default.
  • Java: config.getOrDefault("timeout", "30").
  • C++ has no one-step version. Check whether the key exists with config.count("timeout") (it gives 1 if the key is there and 0 if not), then pick the value or the default.

DSA connection: looking up a key with a fallback value is the building block of frequency counting.

config = {"host": "api.internal", "port": "8443"}
timeout = config.get("timeout", "30")
print(f"Timeout: {timeout}")