Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is the get() method in a dictionary?
What you need to know
Python
1cfg = {"model": "chat-small", "stop": None}2print(cfg.get("temperature")) # None3print(cfg.get("temperature", 0.7)) # 0.74print(cfg.get("stop", ["\n"])) # None -> key exists, its value is None5print("temperature" in cfg) # False -> get() did not insert it6try:7 cfg["temperature"]8except KeyError as e:9 print("KeyError:", e) # KeyError: 'temperature'Three ways to handle a maybe-missing key
| Style | Use when |
|---|---|
d[key] | the key must be there; a crash is the right response |
d.get(key, default) | missing is normal and a default makes sense |
if key in d: / try: ... except KeyError: | missing needs different logic, not just a default value |
Safe nested access
API responses are nested. Chaining get with an empty dict as the default walks down safely:
Python
resp = {"id": "r1", "choices": []}tokens = resp.get("usage", {}).get("total_tokens", 0)print(tokens) # 0Two subtleties
- The default is evaluated before the call, every time.
d.get(k, load_from_db())hits the database even whenkexists. d.get(k) or defaultis not the same asd.get(k, default): theorversion also replaces stored falsy values like0,0.0or"".
A real-life example
A cost dashboard reads token usage from LLM responses. Error and some streaming responses have no usage block:
Python
1PRICE_PER_1K = {"input": 0.15, "output": 0.60} # made-up prices, rupees23def cost(resp):4 usage = resp.get("usage") or {}5 return (usage.get("input_tokens", 0) / 1000 * PRICE_PER_1K["input"]6 + usage.get("output_tokens", 0) / 1000 * PRICE_PER_1K["output"])78responses = [9 {"usage": {"input_tokens": 1200, "output_tokens": 300}},10 {"error": "rate_limited"}, # no usage at all11 {"usage": {"input_tokens": 800, "output_tokens": 0}},12]13print(round(sum(cost(r) for r in responses), 3)) # 0.48resp["usage"] would crash the whole dashboard on the first rate-limited response. But be careful in the opposite direction: when a teammate misspelt the key as "output_token", get(..., 0) silently returned 0 and the dashboard under-reported output cost for a month. A good rule is to use get for fields the API documents as optional, and [] for fields that must exist.
Follow-up questions to expect
- "
getvssetdefault?" —getonly reads;setdefaultinserts the default if the key is missing and returns it. - "
getvstry/except KeyError?" —getis shorter when you just need a default value.try/exceptis better when a missing key needs different handling. - "How do you tell a missing key from a
Nonevalue?" — Usekey in d, or callgetwith a unique sentinel object as the default.