Python for AIPython 3.10+ · Pydantic 2.12
Dashboard
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
34 small wins to finish your pathNext lesson →

Lists of dictionaries

A list of dictionaries is a list whose items are dictionaries with the same keys, the shape most APIs, files and chat models use for records.

Last updated: 30 Sep, 2026 · Python 3.14

Put the dictionary tickets inside a list and you have many records, each with the same named fields.

Looping over records

Example
tickets = [
    {"id": 1, "customer": "Asha", "text": "I was charged twice for one order"},
    {"id": 2, "customer": "Ben", "text": "My parcel has not arrived"},
    {"id": 3, "customer": "Chen", "text": "Can I get a refund for the blue mug?"},
]

for ticket in tickets:
    print(ticket["id"], ticket["customer"])

Each item of the list is a whole dictionary, so inside the loop ticket is one record and ticket["customer"] reads a field from it.

Picking out some records

Example
billing = []
for ticket in tickets:
    text = ticket["text"].lower()
    if "charged" in text or "refund" in text:
        billing.append(ticket)

print(len(billing))
print(billing[1]["customer"])

Start with an empty list, [], and append the records that pass. billing[1]["customer"] reads left to right: the second record, then its customer.

Writing the messages a chat model reads

Chat models take a conversation in this shape: a list of dictionaries, each with a role saying who spoke and a content holding what they said.

Example
messages = [
    {"role": "system", "content": "You sort support tickets."},
    {"role": "user", "content": "My parcel has not arrived"},
    {"role": "assistant", "content": "shipping"},
]

for message in messages:
    print(f"{message['role']}: {message['content']}")

The f-string uses single quotes inside for the keys. That works on every Python version; before Python 3.12, double quotes there would end the string early.

system is the standing instruction, user is the person, and assistant is the model's reply. Adding the next question is one append.

A list of dictionaries vs a dictionary of lists

List of dictionariesDictionary of lists
Shape[{"id": 1, ...}, {"id": 2, ...}]{"id": [1, 2], ...}
One record isOne itemSpread across every list
Adding a recordOne appendOne append per list

Where this shape shows up in AI code

  • The messages list sent to a chat model, and the reply appended to it.
  • Rows read from a JSON file or returned by an API.
Watch out. ticket["customer"] works inside the loop, but tickets["customer"] on the whole list is a TypeError: a list takes a position, not a key.
Try it yourself
  • In the filter example, append a fourth ticket with refund in its text to tickets before the loop, and run it again.
  • Append {"role": "user", "content": "Thanks!"} to messages.
  • Print messages[-1]["content"].
PreviousDictionaries

Every expert started right here.