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.
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
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.
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.
- Append a fourth ticket to
ticketsand run the filter again. - Append
{"role": "user", "content": "Thanks!"}tomessages. - Print
messages[-1]["content"].
This is what real progress feels like.