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
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"])1 Asha 2 Ben 3 Chen
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"])2 Chen
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.
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']}")system: You sort support tickets. user: My parcel has not arrived assistant: shipping
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 dictionaries | Dictionary of lists | |
|---|---|---|
| Shape | [{"id": 1, ...}, {"id": 2, ...}] | {"id": [1, 2], ...} |
| One record is | One item | Spread across every list |
| Adding a record | One append | One append per list |
Where this shape shows up in AI code
- The
messageslist sent to a chat model, and the reply appended to it. - Rows read from a JSON file or returned by an API.
ticket["customer"] works inside the loop, but tickets["customer"] on the whole list is a TypeError: a list takes a position, not a key.Related
- Previous: Dictionaries
- Next: List comprehensions
- Reference: Data Structures in the Python tutorial
- In the filter example, append a fourth ticket with
refundin its text toticketsbefore the loop, and run it again. - Append
{"role": "user", "content": "Thanks!"}tomessages. - Print
messages[-1]["content"].
Every expert started right here.