Course OverviewFree AI CourseBlogReserve Bootcamp Seat
Python for AI · Day 2 of 5 ~60 minutes

Data Structures — Lists, Dicts, JSON

Learn the three data structures that AI APIs use to communicate with you — then parse a real API response.

1
Day 1
2
Day 2
3
Day 3
4
Day 4
5
Day 5
What You'll Build Today

A script that reads a JSON API response (the kind Claude sends back when you call its API), extracts specific fields, and prints them in a useful format. By the end of today, any JSON from any API will be readable to you.

1
Lists

Lists: Ordered Collections

A list holds multiple values in order. It's the most-used data structure in all of Python — and in AI code, you'll use lists to hold messages, documents, results, and more.

pythonlists.py
# Create a list with square brackets
documents = ["report.pdf", "notes.txt", "data.csv"]
scores = [92, 87, 95, 78]

# Access items by index (starts at 0)
print(documents[0])   # report.pdf
print(documents[-1])  # data.csv (last item)

# Add and remove
documents.append("summary.docx")
documents.remove("notes.txt")

# Length
print(len(documents))  # 3

# Loop through a list
for doc in documents:
    print(f"Will process: {doc}")

# This is how Claude's API messages look
messages = [
    {"role": "user", "content": "Analyze this document"},
    {"role": "assistant", "content": "Sure, here's my analysis..."}
]
2
Dictionaries

Dictionaries: Key-Value Pairs

A dictionary maps keys to values. This is how APIs talk to you — every response from Claude, every HTTP response, every config file is a dictionary under the hood.

pythondicts.py
# Create with curly braces
config = {
    "model": "claude-opus-4-5",
    "max_tokens": 1024,
    "temperature": 0.7
}

# Access values by key
print(config["model"])        # claude-opus-4-5
print(config["max_tokens"])   # 1024

# Safe access (won't crash if key missing)
timeout = config.get("timeout", 30)  # returns 30 if not found

# Add and update
config["stream"] = True
config["max_tokens"] = 2048

# Loop through key/value pairs
for key, value in config.items():
    print(f"{key}: {value}")

# Nested dict — this is what API responses look like
api_response = {
    "id": "msg_01abc",
    "model": "claude-opus-4-5",
    "content": [{"type": "text", "text": "The analysis shows..."}],
    "usage": {"input_tokens": 42, "output_tokens": 318}
}

# Dig into nested data
text = api_response["content"][0]["text"]
input_tokens = api_response["usage"]["input_tokens"]

This is exactly what Day 3 looks like. When Claude responds to your API call, you'll get a dictionary like api_response above. You now know how to read it.

3
JSON

JSON: The Language of APIs

JSON (JavaScript Object Notation) is a text format for storing and transmitting data. It looks almost identical to Python dictionaries and lists. Python's built-in json module converts between the two.

pythonjson_demo.py
import json

# JSON string → Python dict (parsing)
json_string = '''
{
  "name": "Sales Report Q1",
  "records": 1247,
  "status": "complete",
  "metrics": {
    "revenue": 482000,
    "growth": 0.14
  }
}
'''

data = json.loads(json_string)  # loads = load string
print(data["name"])              # Sales Report Q1
print(data["metrics"]["growth"]) # 0.14

# Python dict → JSON string (serializing)
result = {
    "processed": True,
    "file_count": 47,
    "errors": []
}
json_output = json.dumps(result, indent=2)
print(json_output)

# Read JSON from a file
with open("config.json") as f:
    config = json.load(f)  # load (not loads) reads a file

# Write JSON to a file
with open("output.json", "w") as f:
    json.dump(result, f, indent=2)
Today's Exercise

Parse a JSON API Response

Given the mock API response below, extract and print: the model used, the response text, input tokens, and output tokens. Then add each to a results list.

  • Parse the JSON string into a Python dict using json.loads()
  • Extract: model, the first content item's text, usage.input_tokens, usage.output_tokens
  • Build a clean result dict with those four fields and save it as JSON
pythonday2.py — starter
import json

mock_response = '''
{
  "id": "msg_01xyz",
  "model": "claude-opus-4-5",
  "content": [
    {"type": "text", "text": "The report shows a 14% revenue increase driven by enterprise contracts in Q1."}
  ],
  "usage": {"input_tokens": 156, "output_tokens": 89},
  "stop_reason": "end_turn"
}
'''

# Your code here:
data = json.loads(mock_response)

# Extract the four fields
model = data["model"]
text = data["content"][0]["text"]
input_tokens = data["usage"]["input_tokens"]
output_tokens = data["usage"]["output_tokens"]

print(f"Model: {model}")
print(f"Response: {text}")
print(f"Tokens: {input_tokens} in / {output_tokens} out")

result = {"model": model, "text": text,
          "input_tokens": input_tokens, "output_tokens": output_tokens}
print(json.dumps(result, indent=2))

What You Learned Today

  • Lists: creating, accessing by index, appending, looping
  • Dictionaries: key-value pairs, nested access, .get() for safe lookups
  • JSON: parsing strings with json.loads(), reading files with json.load(), writing with json.dump()
  • The structure of a real Claude API response — you can now read any of them
Course Progress
Day 2 of 5 — 40%
Day 2 Complete

Day 3: Files and APIs

Tomorrow you'll read real files, make HTTP requests, and call Claude's API for the first time.

Start Day 3