Python Dictionaries
Store data as key-value pairs. Dicts map to JSON, configs, and API payloads.
Why it matters: LLM requests are dicts: model, messages, temperature.
Basics
Keys and Values
A dict maps keys to values:
config = {"model": "mini", "temperature": 0.2}
- Read:
config["model"] - Safe read:
config.get("top_p", 1.0) - Write:
config["max_tokens"] = 256 - Check:
"model" in config
Use .get() for optional fields.
Common mistake: defaulting a required setting and shipping the wrong run.
Tiny example
Create a dict and read a key.
config = {"model": "gpt-4.1-mini"}
print(config["model"])
print(config.get("top_p", 1.0))Basics
Looping Dicts
config.items() gives (key, value) pairs.
Nested access looks like payload["messages"][0]["content"].
Print payload.keys() when you are unsure of the shape.
Common mistake: guessing nested keys instead of inspecting first.
Tiny example
Loop key and value pairs.
metrics = {"accuracy": 0.91, "latency_ms": 120}
for name, value in metrics.items():
print(name, value)Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: LLM request body
This is the shape many chat APIs expect.
In AI / ML: An LLM call is a dict with model and messages.
example.py
Python
request = {
"model": "gpt-4.1-mini",
"messages": [
{"role": "user", "content": "Define RAG."},
],
}
print(request["model"])
print(request.get("temperature", 0.0))AI / ML example 2
AI / ML: metrics dict
Named scores make runs easy to compare.
In AI / ML: Trackers log accuracy and latency as key-value maps.
example.py
Python
metrics = {"accuracy": 0.91, "latency_ms": 128}
metrics["latency_ms"] = 141
print(metrics)Takeaways
- 1Dicts are key-value maps (like JSON objects).
- 2Use .get() for optional fields.
- 3Nested dicts store chat messages.