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

Lists of dictionaries: the shape of real data

Put dictionaries inside a list and you have the shape nearly every API, file and model returns: many records, each with the same named fields.

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.

The messages a chat model reads

Chat models take a conversation as exactly 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, because double quotes 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.

Try it yourself
  • Append a fourth ticket to tickets and run the filter again.
  • Append {"role": "user", "content": "Thanks!"} to messages.
  • Print messages[-1]["content"].

This is what real progress feels like.