Reading a model response safely
import json loads Python's toolbox for JSON (Topic 6.1 teaches import). json.dumps(x, indent=2) turns nested data into indented JSON text.
Real data is nested: a list of dictionaries whose values are lists or more dictionaries. This topic shows how to read, search, update and print such JSON-shaped data safely, which is the shape of every web API and AI model response.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given students = [{"name": "Asha", "marks": [80, 90]}, {"name": "Ravi", "marks": [70, 60, 65]}], print each student's name and average mark.
From the same data, build a dictionary mapping each name to the highest mark.
Given config = {"db": {"host": "localhost"}}, print the port with a default of 5432 without raising an error.
Explain it without notes
How do you read the second tag of the first item in a list of dictionaries?
How do you safely read a value that may be missing, several levels deep?
How does JSON map onto Python types?
Why can changing found["stock"] change the list?
Expected output
reply: Hello!
total tokens: 15
cached tokens: not reported
error: none
first choice of an empty reply: None
{
"message": {
"role": "assistant",
"content": "Hello!"
},
"finish_reason": "stop"
}