Dictionaries
Key–value maps are how Python represents JSON, API payloads, model configs, and metadata.
Why this matters in AI / ML / GenAI
Every LLM HTTP request is a dict that becomes JSON: model, messages, temperature. Hugging Face model cards, MLflow params, and feature rows are dicts. If you can navigate nested dicts, you can work with real APIs.
Keys, values, and safe lookup
A dict maps keys to values: config = {"model": "gpt-4.1-mini", "temperature": 0.2}.
Keys are usually strings. Values can be anything, including lists and other dicts (nested JSON).
- Read:
config["model"]raisesKeyErrorif missing - Safe read:
config.get("top_p", 1.0)returns the default - Write:
config["max_tokens"] = 256 - Check:
"model" in config
Prefer .get() for optional API fields. Prefer ["key"] when the key must exist — failing loudly is better than silently using the wrong default in a training job.
Looping and nesting
config.items() gives (key, value) pairs. config.keys() and config.values() exist too.
Nested access: payload["messages"][0]["content"]. Walk one level at a time when debugging.
Building JSON-ready dicts is a core GenAI skill. Keep structures close to the API you call so you are not translating shapes in three places.
Copy-paste examples
Copy into your own editor, or load one into the compiler below and press Run.
An LLM request body
This is the shape OpenAI-style APIs expect, before json.dumps.
request = {
"model": "gpt-4.1-mini",
"temperature": 0.2,
"messages": [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "Define RAG in one sentence."},
],
}
print(request["model"])
print(request["messages"][-1]["content"])
print("top_p" in request)
print("top_p default:", request.get("top_p", 1.0))Metrics dict (what you log to MLflow-style tracking)
Keep metric names stable so dashboards do not fragment.
metrics = {"accuracy": 0.91, "latency_ms": 128, "tokens_in": 412}
metrics["latency_ms"] = 141
for name, value in metrics.items():
print(f"{name}={value}")Merge default config with overrides
{**defaults, **overrides} is a common pattern for experiment configs.
defaults = {"epochs": 3, "lr": 2e-5, "fp16": True}
overrides = {"lr": 1e-5, "run_name": "exp-12"}
config = {**defaults, **overrides}
print(config)Read a nested chat payload
Try it — in-browser Python
Print the system message and count how many messages are in the list.
Output
Python runs in your browser. First run downloads the runtime.
Press Run (or Ctrl+Enter) to execute.
CPython in WebAssembly. Stdlib works. NumPy and pandas load on demand. No input(), no GPU, no network installs.
Takeaways
- Dicts are JSON objects in Python form — the language of APIs.
- Use .get(key, default) for optional fields; [] when the key is required.
- Nested dicts + lists are how chat messages and tool calls are stored.