Python for AIPython for AI
Data Structures

Nested data

Lists of dictionaries and other combinations

Real data is rarely a single list or a single dictionary. It's usually both together. This shape is so common in AI work that it's worth learning properly: API responses, chat histories, and document chunks all use it.

What is nested data?

Nested data means putting one data structure inside another. The most important combination is a list of dictionaries:

  • The list keeps items in order.
  • Each dictionary describes one item with named fields.
python
students = [
    {"name": "Ana", "score": 91},
    {"name": "Ben", "score": 78},
    {"name": "Chen", "score": 85},
]
students  (list)
├── [0]  (dict)
│   ├── name  → "Ana"
│   └── score → 91
├── [1]  (dict)
│   ├── name  → "Ben"
│   └── score → 78
└── [2]  (dict)
    ├── name  → "Chen"
    └── score → 85
A list holds dictionaries. Each dictionary holds key–value pairs.

Reading values

Read from the outside in: first pick the list item with its index, then the dictionary field with its key.

python
print(students[0])            # {'name': 'Ana', 'score': 91}
print(students[0]["name"])    # Ana
print(students[-1]["score"])  # 85
Read students[1]["score"] from left to right: "from students, take item 1, then its score".

Looping over a list of dictionaries

A for loop gives you one dictionary per round.

python
for student in students:
    print(f"{student['name']} scored {student['score']}")

Filtering and collecting

python
passed = []
for student in students:
    if student["score"] >= 80:
        passed.append(student["name"])

print(passed)  # ['Ana', 'Chen']

Adding and changing items

python
# add a new dictionary to the list
students.append({"name": "Dev", "score": 88})

# change a value inside one dictionary
students[1]["score"] = 82

print(len(students))  # 4

Going deeper

Dictionaries can also hold lists, and those lists can hold more dictionaries. API responses often look like this.

python
response = {
    "model": "gpt-4o-mini",
    "choices": [
        {"message": {"role": "assistant", "content": "Hello there!"}}
    ],
}

reply = response["choices"][0]["message"]["content"]
print(reply)  # Hello there!

Take it one step at a time: response["choices"] is a list, [0] is its first dictionary, ["message"] is another dictionary, and ["content"] is the text.

Why this matters for AI

When you talk to a language model, the conversation is a list of dictionaries. Each dictionary is one message:

python
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is Python?"},
]

Once you are comfortable reading lists of dictionaries, most AI and API data will look familiar.

Common mistakes

  • Using a key on the list itself: students["name"] raises a TypeError. Pick an item first: students[0]["name"].
  • Misspelling a key raises a KeyError. Use .get("key") if a field might be missing.
  • Mixing up quotes inside f-strings: use student['name'] inside f"...".

What's next?

Next, you'll learn control flow: how to make decisions with if statements and repeat work with loops, for example looping over every dictionary in a list.