dict.get()
dict.get(key, default) looks up a key in a dict and, if it's missing, gives you a default value instead of raising an error.
Used in 110 lessons of the course, from 00.02.
With d["key"] Python raises a KeyError if the key doesn't exist. With d.get("key") it doesn't: it returns None. If you pass a second argument, d.get("key", "x"), that value is returned when the key is missing.
Read it as: "give me the value for this key; if it isn't there, use this other one". The dict doesn't change: get only looks, it stores nothing.
It's written this way because a key is often optional and its absence isn't an error. Environment variables are a good case: os.environ.get("CONDA_DEFAULT_ENV", "<not set>") in lesson 00.02 shows a clear text when the variable is missing, instead of stopping the program.
config = {"model": "demo"}
print(config.get("model"))
Reach for it when: a key may be missing and you want a fallback value instead of an error.
Examples
Common mistake
config = {"model": "demo"}
print(config["temperature"])Why: Square brackets require the key to exist; if it's missing, Python raises KeyError.
How to write it: Use config.get("temperature", 0.7) when the key is optional.
Common mistake
config = {"model": "demo"}
name = config.get("nmae")
print("Model:", name)Why: With a misspelled key, get doesn't warn you: it quietly returns None and the typo goes unnoticed.
How to write it: Check the key name, or use config["model"] when the key is required so it fails loudly.
