Python Essentials for AI Engineer

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
cfg = {"model": "chat-small", "stop": None}print(cfg.get("temperature"))        # Noneprint(cfg.get("temperature", 0.7))   # 0.7print(cfg.get("stop", ["\n"]))       # None   -> key exists, its value is Noneprint("temperature" in cfg)          # False  -> get() did not insert ittry:    cfg["temperature"]except KeyError as e:    print("KeyError:", e)            # KeyError: 'temperature'

Three ways to handle a maybe-missing key

StyleUse 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)          # 0

Two subtleties

  • The default is evaluated before the call, every time. d.get(k, load_from_db()) hits the database even when k exists.
  • d.get(k) or default is not the same as d.get(k, default): the or version also replaces stored falsy values like 0, 0.0 or "".

A real-life example

A cost dashboard reads token usage from LLM responses. Error and some streaming responses have no usage block:

Python
PRICE_PER_1K = {"input": 0.15, "output": 0.60}   # made-up prices, rupeesdef cost(resp):    usage = resp.get("usage") or {}    return (usage.get("input_tokens", 0) / 1000 * PRICE_PER_1K["input"]            + usage.get("output_tokens", 0) / 1000 * PRICE_PER_1K["output"])responses = [    {"usage": {"input_tokens": 1200, "output_tokens": 300}},    {"error": "rate_limited"},                       # no usage at all    {"usage": {"input_tokens": 800, "output_tokens": 0}},]print(round(sum(cost(r) for r in responses), 3))      # 0.48

resp["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

  • "get vs setdefault?" — get only reads; setdefault inserts the default if the key is missing and returns it.
  • "get vs try/except KeyError?" — get is shorter when you just need a default value. try/except is better when a missing key needs different handling.
  • "How do you tell a missing key from a None value?" — Use key in d, or call get with a unique sentinel object as the default.