Lists, dicts and nested structures
Dictionaries are the backbone of every API message in AI. When you see messages=[{"role": "user", "content": "Hello"}], that is a list of dictionaries. Let us master these structures.
Data structures for AI APIs
How lists and dicts combine to form API messages
# Lists: ordered collections
menu_items = [
"Avocado Toast with Chili Flakes",
"Quinoa Power Bowl",
"Creamy Cashew Mac & Cheese",
]
print(menu_items[0]) # first item
print(menu_items[-1]) # last item
print(len(menu_items)) # 3
menu_items.append("Spicy Tofu Tacos") # add to end
print(menu_items)
# Slicing
print(menu_items[1:3]) # items at index 1 and 2Lists use square brackets and are ordered. Access items by index (0-based), add with .append(), and slice with [start:end].
Lists are ordered by position (index 0, 1, 2...). Dictionaries are organized by named keys. In AI code, lists hold collections (messages, tools), while dicts hold structured data (config, API responses). Most real AI code uses both together.
# Dictionaries: key-value pairs
agent_config = {
"role": "SQL Expert",
"system_prompt": "You are a senior SQL developer.",
"temperature": 0,
}
print(agent_config["role"]) # SQL Expert
print(agent_config.get("model", "gpt-4o-mini")) # safe access with default
# Iteration
for key, value in agent_config.items():
print(f" {key}: {value}")Dicts use curly braces with key: value pairs. Use .get() for safe access with a default when the key might not exist.
Absolutely, and that is actually the most common pattern in AI code. A list of dicts is how every LLM API structures conversation messages. Let me show you.
# Nested structures (the #1 pattern in AI code)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What are the top products?"},
]
# Accessing nested data
print(messages[1]["content"]) # What are the top products?
# Adding to the conversation
messages.append({"role": "assistant", "content": "Here are the top products..."})
print(f"Conversation has {len(messages)} messages")A list of dicts is THE pattern in AI. Every LLM API uses messages=[{role, content}]. You will build conversations by appending dicts to this list.
Quiz: Quiz
Loading practiceโฆ