> Source URL: /resources/lists-of-dicts.guide
# Lists of Dictionaries

A list of dictionaries lets you store a collection of records, like rows in a table. Each dictionary represents one item with named fields.

## Why Lists of Dicts?

A single dictionary is great for one record. But most programs work with _many_ records — agents, recruits, inventory items. A list of dictionaries gives you a structured way to store and process them all.

```python
agents = [
    {"name": "Sable", "department": "Signals", "score": 88},
    {"name": "Kael", "department": "Nodes", "score": 72},
    {"name": "Mira", "department": "Simulations", "score": 95}
]
```

Think of it like a table:

| name  | department  | score |
|-------|-------------|-------|
| Sable | Signals     | 88    |
| Kael  | Nodes       | 72    |
| Mira  | Simulations | 95    |

## Creating Records with a Function

Instead of building each dictionary by hand, use a function to keep the format consistent:

```python
def create_agent(name, department, score):
    return {
        "name": name,
        "department": department,
        "score": score,
        "status": "active"
    }

agents = []
agents.append(create_agent("Sable", "Signals", 88))
agents.append(create_agent("Kael", "Nodes", 72))

print(agents[0])
```

Output:

```
{'name': 'Sable', 'department': 'Signals', 'score': 88, 'status': 'active'}
```

## Looping and Displaying

Use a `for` loop to go through each record:

```python
agents = [
    {"name": "Sable", "department": "Signals", "score": 88},
    {"name": "Kael", "department": "Nodes", "score": 72},
    {"name": "Mira", "department": "Simulations", "score": 95}
]

for agent in agents:
    print(agent["name"] + " — " + agent["department"])
```

Output:

```
Sable — Signals
Kael — Nodes
Mira — Simulations
```

You can also write a display function for reuse:

```python
def display_agent(agent):
    print("Name: " + agent["name"])
    print("Dept: " + agent["department"])
    print("Score: " + str(agent["score"]))
    print("Status: " + agent.get("status", "unknown"))
    print()

for agent in agents:
    display_agent(agent)
```

## Searching

Find a record by checking each item in the list:

```python
def search_agents(agents, term):
    for agent in agents:
        if term.lower() in agent["name"].lower():
            return agent
    return None

result = search_agents(agents, "kael")

if result:
    print("Found: " + result["name"])
else:
    print("No match found.")
```

Output:

```
Found: Kael
```

Returning `None` when nothing matches lets the caller decide what to do.

## Filtering

Build a new list containing only the records you want:

```python
def get_high_scorers(agents, threshold):
    results = []
    for agent in agents:
        if agent["score"] >= threshold:
            results.append(agent)
    return results

top_agents = get_high_scorers(agents, 85)

for agent in top_agents:
    print(agent["name"] + ": " + str(agent["score"]))
```

Output:

```
Sable: 88
Mira: 95
```

## Aggregating

Calculate totals, averages, or counts across your records:

```python
def generate_summary(agents):
    total = 0
    count = 0
    for agent in agents:
        if agent["score"] >= 0:
            total = total + agent["score"]
            count = count + 1

    if count > 0:
        average = total / count
    else:
        average = 0

    print("Agents: " + str(count))
    print("Average score: " + str(average))

generate_summary(agents)
```

Output:

```
Agents: 3
Average score: 85.0
```

_Tip: Checking `agent["score"] >= 0` lets you skip invalid or placeholder values._

## Loading from a File

In real programs, records usually come from a file instead of being hardcoded. A common pattern is reading a text file where each line is a comma-separated record:

```
Sable,Signals,88
Kael,Nodes,72
Mira,Simulations,95
```

```python
def load_agents(filename):
    agents = []
    with open(filename, "r") as file:
        for line in file:
            parts = line.strip().split(",")
            agent = {
                "name": parts[0],
                "department": parts[1],
                "score": int(parts[2])
            }
            agents.append(agent)
    return agents

agents = load_agents("agents.txt")
print(agents[0])
```

Output:

```
{'name': 'Sable', 'department': 'Signals', 'score': 88}
```

## Saving to a File

Write your records back to a file in the same format:

```python
def save_agents(filename, agents):
    with open(filename, "w") as file:
        for agent in agents:
            line = agent["name"] + "," + agent["department"] + "," + str(agent["score"])
            file.write(line + "\n")

save_agents("agents.txt", agents)
```

## The Full Pipeline

Most Unit 2 programs follow the same flow:

1. **Load** records from a file into a list of dicts
2. **Process** the data (search, filter, update, aggregate)
3. **Display** results or **save** them back to a file

```python
def main():
    agents = load_agents("agents.txt")
    top = get_high_scorers(agents, 85)
    for agent in top:
        display_agent(agent)
    save_agents("top_agents.txt", top)

main()
```

## Common Mistakes

**Accessing a key that might not exist**

```python
# Wrong — crashes if "status" is missing
print(agent["status"])

# Right — use .get() with a default
print(agent.get("status", "unknown"))
```

**Forgetting `.strip()` when loading from a file**

```python
# Wrong — the last field keeps the newline
parts = line.split(",")

# Right — strip first, then split
parts = line.strip().split(",")
```

**Confusing a single dict with the list**

```python
agents = [{"name": "Sable"}, {"name": "Kael"}]

# Wrong — agents is a list, not a dict
print(agents["name"])

# Right — index into the list first
print(agents[0]["name"])
```

**Forgetting to convert types when loading**

```python
# Wrong — score stays a string
agent = {"name": parts[0], "score": parts[2]}

# Right — convert to int
agent = {"name": parts[0], "score": int(parts[2])}
```


---

## Backlinks

The following sources link to this document:

- [Lists of Dictionaries Guide](/resources/resources.index.llm.md)
