---
title: "Project: A Data Explorer"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 30
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/30-project-a-data-explorer
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 30 — Project: A Data Explorer

The librarian of Brenmoor has two tables, the books and the loans of 2025, and many questions. This chapter builds, in five versions, a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that answers them. Each version runs, each is tested, and each adds one thing to the one before. Here is what the finished [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) must do:

> The explorer loads the library’s books and loans and offers a [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu). It can count the loans of each genre, [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) the ten most borrowed books, [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) the books never borrowed, and count the loans still out on a date that the user types. It answers each question, and saves the last answer to a report [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file).

**You already know.**

A [CSV file](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-table) keeps a [data table](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-table) as text, and `csv.DictReader` turns it into a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of records ([Chapter 27](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#ch-g8-files-and-data-tables)). A [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) gives the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of a key, and counts things with `get` ([Chapter 26](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#ch-g8-dictionaries)). `sorted` returns a [sorted](https://one-course.com/books/computer-science/1/en/chapter/28-searching-and-sorting#def-g8-searching-and-sorting-sorted) copy of a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) ([Chapter 28](https://one-course.com/books/computer-science/1/en/chapter/28-searching-and-sorting#ch-g8-searching-and-sorting)). A project grows in versions, each one tested ([Chapter 24](https://one-course.com/books/computer-science/1/en/chapter/24-project-a-quiz-game#ch-g7-project-quiz-game)).

## 30.1 What must it do?

The paragraph above, turned into checks small enough to test:

1. A [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu) shows the four questions and a choice to quit; any other choice gets a polite message, and the [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu) goes on until the user quits.
2. The two tables are loaded, and the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) checks that it has as many records as the [files](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) have lines after their [header rows](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-table) .
3. The loans of each genre add up to the number of loans.
4. The top ten is [sorted](https://one-course.com/books/computer-science/1/en/chapter/28-searching-and-sorting#def-g8-searching-and-sorting-sorted) from the most borrowed; two books with as many loans are in the order of their titles.
5. A date that is not written `YYYY-MM-DD` is refused with a message.
6. After each answer, `report.txt` holds that answer.

![The path of the data through the explorer: from two files to an answer on the screen and in a report file.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-project-data-explorer/fig-b86ddf4e0deb.svg)

*The path of the data through the explorer: from two [files](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) to an answer on the screen and in a report [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file).*

## 30.2 The menu and its loop

Version 1 has no data yet: only the [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu), the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) that reads the choices, and a way out.

```python
MENU = """1. loans by genre
2. the ten most borrowed books
3. books never borrowed
4. loans still out on a date
0. quit"""


def main():
    print(MENU)
    choice = ""
    while choice != "0":
        choice = input("choice: ").strip()
        if choice in ["1", "2", "3", "4"]:
            print("question", choice, "is not ready yet")
        elif choice != "0":
            print("please type a number from 0 to 4")
    print("goodbye")


if __name__ == "__main__":
    main()
```

***Listing 30.1.** Version 1: the [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu). code/grade-8/06-project-data-explorer/listings/explorer_v1.py*

```
$ python explorer_v1.py
1. loans by genre
2. the ten most borrowed books
3. books never borrowed
4. loans still out on a date
0. quit
choice: 2
question 2 is not ready yet
choice: 7
please type a number from 0 to 4
choice: 0
goodbye
```

***Output 30.1.** A session: a question, a wrong choice, then quit.*

The three quotes `"""` open a [string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) that goes on over several lines. The [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) goes on while the choice is not `"0"`; the test `choice in ["1", "2", "3", "4"]` checks that the choice is one of the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list).

![The menu loop: read a choice, stop on 0, answer a question, or ask again.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-project-data-explorer/fig-5b71d091e8ca.svg)

*The [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu) [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop): read a choice, stop on `0`, answer a question, or ask again.*

## 30.3 Loading the two tables

Version 2 loads the tables before the [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu). Two new [functions](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) do it:

```python
def load_table(filename):
    """The records of a CSV file, as a list of dictionaries."""
    with open(filename, encoding="utf-8") as f:
        return list(csv.DictReader(f))


def count_lines(filename):
    """The number of records: the lines of the file, minus the header row."""
    with open(filename, encoding="utf-8") as f:
        return len(f.readlines()) - 1


def main():
    books = load_table("books.csv")
    loans = load_table("loans.csv")
    assert len(books) == count_lines("books.csv")
    assert len(loans) == count_lines("loans.csv")
    print("loaded", len(books), "books and", len(loans), "loans")
```

***Listing 30.2.** Version 2: loading and checking the tables (the start of `main`). code/grade-8/06-project-data-explorer/listings/explorer_v2.py*

```
$ python explorer_v2.py
loaded 80 books and 400 loans
1. loans by genre
2. the ten most borrowed books
3. books never borrowed
4. loans still out on a date
0. quit
choice: 0
goodbye
```

***Output 30.2.** 80 books and 400 loans, then quit at once.*

`assert` followed by a [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) stops the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) with an error if the [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) is false, and does nothing otherwise: a check written into the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program). Here it compares the number of records with the number of lines of the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file), so the 80 and the 400 are read from the data, never typed by hand. If someone adds a book to the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file), the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) still agrees with it.

## 30.4 Filtering and counting

Each loan names its book only by a number, `book_id`. To count the loans of each genre, the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) looks up the book of each loan. A [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) from `book_id` to the book’s record makes each look-up a single step, instead of a search through the 80 books.

![Looking up the book of each loan: the book_id of a loan leads to the row of its book, and so to its genre.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-project-data-explorer/fig-8c614404df8d.svg)

*Looking up the book of each loan: the `book_id` of a loan leads to the row of its book, and so to its genre.*

```python
def book_finder(books):
    """A dictionary that gives the record of a book from its book_id."""
    finder = {}
    for book in books:
        finder[book["book_id"]] = book
    return finder


def loans_by_genre(books, loans):
    """The number of loans of each genre: each loan looks up its book."""
    finder = book_finder(books)
    counts = {}
    for loan in loans:
        genre = finder[loan["book_id"]]["genre"]
        counts[genre] = counts.get(genre, 0) + 1
    return counts


def never_borrowed(books, loans):
    """The titles of the books that no loan mentions."""
    borrowed = {}
    for loan in loans:
        borrowed[loan["book_id"]] = True
    titles = []
    for book in books:
        if book["book_id"] not in borrowed:
            titles.append(book["title"])
    return titles
```

***Listing 30.3.** Version 3: looking up books, loans per genre, books never borrowed. code/grade-8/06-project-data-explorer/listings/explorer_v3.py*

The [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu) [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) now calls a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `answer`, which builds the lines of an answer:

```python
def answer(choice, books, loans):
    """The lines of the answer to one question."""
    lines = []
    if choice == "1":
        counts = loans_by_genre(books, loans)
        for genre in sorted(counts):
            lines.append(f"{genre:<10} {counts[genre]:>4}")
    elif choice == "3":
        titles = never_borrowed(books, loans)
        for title in titles:
            lines.append(title)
        if titles == []:
            lines.append("every book was borrowed at least once")
    else:
        lines.append("question " + choice + " is not ready yet")
    return lines
```

***Listing 30.4.** Version 3: the answers as lines. code/grade-8/06-project-data-explorer/listings/explorer_v3.py*

```
$ python explorer_v3.py
loaded 80 books and 400 loans
choice: 1
adventure    65
comics       45
history      53
mystery      40
nature       38
poetry       49
science      66
sport        44
choice: 3
every book was borrowed at least once
choice: 0
goodbye
```

***Output 30.3.** Questions 1 and 3. Some lines are left out.*

`answer` returns its lines instead of printing them: the last version will both print them and save them. Question 3 has an empty answer: every book of the library went out at least once in 2025. Saying so is better than printing nothing, which would look like a [bug](https://one-course.com/books/computer-science/1/en/chapter/23-finding-and-fixing-bugs#def-g7-finding-and-fixing-bugs-bug).

![The loans of 2025 by genre, counted by the explorer’s own function loans_by_genre.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-project-data-explorer/fig-f17bc6abaf09.svg)

*The loans of 2025 by genre, counted by the explorer’s own [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `loans_by_genre`.*

## 30.5 Sorting and the top ten

The ten most borrowed books need the books [sorted](https://one-course.com/books/computer-science/1/en/chapter/28-searching-and-sorting#def-g8-searching-and-sorting-sorted) by their number of loans, from the most. `sorted` can take a `key`: a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) that it calls on each [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), and whose results it compares instead of the [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). Here the key of a row is the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) `[-loans, title]`. [Lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) are compared [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) by [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), like the [characters](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) of a text ([Chapter 27](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#ch-g8-files-and-data-tables)): the first [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) decide, and only when they are equal do the second ones. The minus sign puts the largest numbers of loans first; the title breaks the ties.

```python
def most_borrowed_first(row):
    """The sort key: the most loans first, then the title in alphabetical order."""
    return [-row["loans"], row["title"]]


def top_ten(books, loans):
    """The ten most borrowed books, as records with a title and a number of loans."""
    counts = {}
    for loan in loans:
        counts[loan["book_id"]] = counts.get(loan["book_id"], 0) + 1
    rows = []
    for book in books:
        rows.append({"title": book["title"], "loans": counts.get(book["book_id"], 0)})
    return sorted(rows, key=most_borrowed_first)[:10]
```

***Listing 30.5.** Version 4: the sort key and the top ten. code/grade-8/06-project-data-explorer/listings/explorer_v4.py*

```
$ python explorer_v4.py
choice: 2
 1. The Clockwork Engine          10
 2. A Map of the Comet             9
 3. Beyond the Island              9
 4. Notes on the Tower             9
 5. Seven Forest                   9
 6. A Map of the Harbour           8
 7. A Map of the Lighthouse        8
 8. A Year by the Orchard          8
 9. Seven Valley                   8
10. The Hidden Machine             8
choice: 0
goodbye
```

***Output 30.4.** The top ten. Some lines are left out.*

The key is a named [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function), given to `sorted` without brackets: `key=most_borrowed_first` hands over the [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) itself, for `sorted` to call; `most_borrowed_first()` would call it at once. `[:10]` keeps the first ten rows of the [sorted list](https://one-course.com/books/computer-science/1/en/chapter/28-searching-and-sorting#def-g8-searching-and-sorting-sorted). Four books have 9 loans: they come in the alphabetical order of their titles.

## 30.6 Dates and the report

The last version adds question 4 and the report. Dates in the loans table are written `YYYY-MM-DD`, so they can be compared as text ([Chapter 27](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#ch-g8-files-and-data-tables)); a date typed by the user is checked first, so that it is written the same way.

```python
def is_date(text):
    """True when text looks like a date written YYYY-MM-DD."""
    if len(text) != 10 or text[4] != "-" or text[7] != "-":
        return False
    return (text[:4] + text[5:7] + text[8:]).isdigit()


def still_out_on(loans, date):
    """The loans that went out on or before date and had not come back by then."""
    out = []
    for loan in loans:
        if loan["out_date"] <= date:
            if loan["return_date"] == "" or loan["return_date"] > date:
                out.append(loan)
    return out


def save_report(lines, filename):
    """Write the lines of an answer to a text file, one per line."""
    with open(filename, "w", encoding="utf-8") as f:
        for line in lines:
            f.write(line + "\n")
```

***Listing 30.6.** Version 5: checking a date, the loans still out, and the report. code/grade-8/06-project-data-explorer/listings/explorer_v5.py*

```python
def main():
    books = load_table("books.csv")
    loans = load_table("loans.csv")
    assert len(books) == count_lines("books.csv")
    assert len(loans) == count_lines("loans.csv")
    print("loaded", len(books), "books and", len(loans), "loans")
    print(MENU)
    saved = False
    choice = ""
    while choice != "0":
        choice = input("choice: ").strip()
        if choice in ["1", "2", "3", "4"]:
            lines = answer(choice, books, loans)
            for line in lines:
                print(line)
            save_report(lines, "report.txt")
            saved = True
            print("(saved to report.txt)")
        elif choice != "0":
            print("please type a number from 0 to 4")
    print("goodbye")
    if saved:
        with open("report.txt", encoding="utf-8") as f:
            print("report.txt holds:", f.read().strip())


if __name__ == "__main__":
    main()
```

***Listing 30.7.** Version 5: the [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu) [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) now saves each answer. code/grade-8/06-project-data-explorer/listings/explorer_v5.py*

```
$ python explorer_v5.py
loaded 80 books and 400 loans
choice: 4
date (YYYY-MM-DD): 2025-06-30
35 loans still out on 2025-06-30
(saved to report.txt)
choice: 4
date (YYYY-MM-DD): 30/6/2025
not a date written YYYY-MM-DD: 30/6/2025
(saved to report.txt)
choice: 4
date (YYYY-MM-DD): 2025-12-31
24 loans still out on 2025-12-31
(saved to report.txt)
choice: 0
goodbye
report.txt holds: 24 loans still out on 2025-12-31
```

***Output 30.5.** Two dates and one refused; the report keeps the last answer. Some lines are left out.*

A loan is still out on a date if it went out on or before that date and had not come back by then: either it never came back, or it came back later. On 31 December, 24 loans are out; 22 of them never came back, and 2 came back in 2026. The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) checks the date before using it, and the [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) `saved` makes sure that `report.txt` is only read once something has been written to it.

The tests of the chapter check each [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) on the tables: that the genre counts add up to 400, that the top ten is in order, that each version’s session prints what it should, and that the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program)’s copies of the two tables are exactly the town’s [files](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file).

## 30.7 Exercises

**Exercise 30.1 ★.**

Version 1 is given the choices `5`, `1`, then `0`. What does it print after the [menu](https://one-course.com/books/computer-science/1/en/chapter/4-using-a-computer#def-g2-using-a-computer-menu)?

**Solution of Exercise 30.1.**

For the 5, it prints `please type a number from 0 to 4`; for the 1, it prints `question 1 is not ready yet`; for the 0, `goodbye`. A test of the chapter plays this session.

**Exercise 30.2 ★.**

A toy library has three books, Ash (`book_id` 1), Birch (2) and Cedar (3), and five loans, of the books 2, 3, 2, 1 and 3. What are the first three rows of `top_ten`?

**Solution of Exercise 30.2.**

Birch and Cedar have 2 loans each, Ash 1. The keys are `[-2, "Birch"]`, `[-2, "Cedar"]` and `[-1, "Ash"]`: Birch, then Cedar (same first [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), `"Birch"` before `"Cedar"`), then Ash.

**Exercise 30.3 ★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `books_by(books, author)` that returns the titles of the books written by one author.

**Solution of Exercise 30.3.**

```python
def books_by(books, author):
    """The titles of the books written by author."""
    titles = []
    for book in books:
        if book["author"] == author:
            titles.append(book["title"])
    return titles
```

*The books of one author. code/grade-8/06-project-data-explorer/exercises/by_author.py*

**Exercise 30.4 ★.**

This version of `top_ten` prints The Clockwork Engine in first and second place. Why? Fix it.

```python
def top_ten(books, loans):
    counts = {}
    for loan in loans:
        counts[loan["book_id"]] = counts.get(loan["book_id"], 0) + 1
    finder = {}
    for book in books:
        finder[book["book_id"]] = book
    rows = []
    for loan in loans:
        book = finder[loan["book_id"]]
        rows.append({"title": book["title"], "loans": counts[loan["book_id"]]})
    return sorted(rows, key=most_borrowed_first)[:10]
```

***Listing 30.8.** A top ten that repeats books. code/grade-8/06-project-data-explorer/exercises/top_ten_bug.py*

**Solution of Exercise 30.4.**

The rows are built from the loans, one row per loan: a book borrowed 10 times gets 10 identical rows, all at the top. The rows must be built from the books, one per book, as in version 4.

**Exercise 30.5 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `busiest_month(loans)` that returns the month in which the most loans went out, and their number.

**Solution of Exercise 30.5.**

```python
def busiest_month(loans):
    """The month (01 to 12) in which the most loans went out, and their number."""
    counts = {}
    for loan in loans:
        month = loan["out_date"][5:7]
        counts[month] = counts.get(month, 0) + 1
    best = "01"
    for month in counts:
        if counts[month] > counts.get(best, 0):
            best = month
    return best, counts[best]
```

*The busiest month. code/grade-8/06-project-data-explorer/exercises/busiest_month.py*

On the town’s table it returns `('09', 45)`: September, with 45 loans.

**Exercise 30.6 ★★.**

Without `is_date`, version 5 answers `22 loans still out on 30/6/2025`. Explain this number, by comparing `"30/6/2025"` with the dates of the table as text.

**Solution of Exercise 30.6.**

Every date of the table starts with `2`, and `"30/6/2025"` with `3`. As text, every out date is therefore smaller: every loan seems to have gone out before that “date”. No return date is larger, so only the loans that never came back are counted: the 22 of [Chapter 27](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#ch-g8-files-and-data-tables). The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) gives a plausible number, and it is wrong; that is why the date is checked first.

**Exercise 30.7 ★★.**

The town also has a members table, `members.csv`, with a `member_id` column. Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `never_borrowers(members, loans)` that returns the members who never borrowed a book.

**Solution of Exercise 30.7.**

The same pattern as `never_borrowed`, on members:

```python
def never_borrowers(members, loans):
    """The member_id of the members that no loan mentions."""
    borrowed = {}
    for loan in loans:
        borrowed[loan["member_id"]] = True
    ids = []
    for member in members:
        if member["member_id"] not in borrowed:
            ids.append(member["member_id"])
    return ids
```

*Members without a loan. code/grade-8/06-project-data-explorer/exercises/never_borrowers.py*

On the town’s tables it returns an empty [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list): all 60 members borrowed at least once.

**Exercise 30.8 ★★.**

For 80 books and 400 loans, how many times does `loans_by_genre` read or write the dictionaries `finder` and `counts`? Count the steps of `book_finder` too.

**Solution of Exercise 30.8.**

`book_finder` writes 80 times, once per book. Then, for each of the 400 loans, `loans_by_genre` reads `finder` once, reads `counts` once with `get`, and writes it once: $3 \times 400 = 1{,}200$. In all, $80 + 1{,}200 = 1{,}280$ steps, each a single step whatever the size of the [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary). Searching the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of books for each loan instead could take up to 80 [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) per loan.

**Exercise 30.9 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `save_csv(rows, filename)` that saves the top ten as a [CSV file](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-table), with the [header row](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-table) `title,loans`.

**Solution of Exercise 30.9.**

`csv.DictWriter` takes the [header row](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-table) from the keys of the first row:

```python
import csv


def save_csv(rows, filename):
    """Write records that all have the same keys to a CSV file."""
    with open(filename, "w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        writer.writeheader()
        for row in rows:
            writer.writerow(row)
```

*The top ten as a [CSV file](https://one-course.com/books/computer-science/1/en/chapter/27-files-and-data-tables#def-g8-files-and-data-tables-table). code/grade-8/06-project-data-explorer/exercises/save_csv.py*

**Exercise 30.10 ★★★.**

The module `datetime` of Python knows the calendar: after `from datetime import date`, the call `date.fromisoformat("2025-01-03")` turns a text into a date, and the difference of two dates has a number of days, `.days`. Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `average_length(loans)` that returns the average number of days a book stays out, over the loans that came back.

**Solution of Exercise 30.10.**

```python
from datetime import date


def average_length(loans):
    """The average number of days between going out and coming back."""
    days = 0
    returned = 0
    for loan in loans:
        if loan["return_date"] != "":
            start = date.fromisoformat(loan["out_date"])
            end = date.fromisoformat(loan["return_date"])
            days = days + (end - start).days
            returned = returned + 1
    return round(days / returned, 1)
```

*The average length of a loan. code/grade-8/06-project-data-explorer/exercises/loan_length.py*

On the 378 loans that came back, the average is 17.6 days.

**Exercise 30.11 ★★★.**

Explain why `top_ten` gives the same ten rows, in the same order, whatever the order of the lines of `loans.csv`.

**Solution of Exercise 30.11.**

Each loan adds 1 to the count of its book, wherever it is in the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file), so the counts do not depend on the order. The rows are built in the order of the books, and then [sorted](https://one-course.com/books/computer-science/1/en/chapter/28-searching-and-sorting#def-g8-searching-and-sorting-sorted) by the key `[-loans, title]`. The 80 titles are all different, so no two rows have the same key: the [sorted](https://one-course.com/books/computer-science/1/en/chapter/28-searching-and-sorting#def-g8-searching-and-sorting-sorted) order is decided by the keys alone, and the first ten rows are always the same.

**Exercise 30.12 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `best_pair(loans)` that finds the pair of books borrowed by the largest number of the same members, and that number.

**Solution of Exercise 30.12.**

First the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of different books of each member; then, for each member, every pair of those books, counted in a [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) whose keys are texts such as `"5+47"`:

```python
def best_pair(loans):
    """The pair of books borrowed by the most members, and that number of members."""
    books_of = {}
    for loan in loans:
        member = loan["member_id"]
        if member not in books_of:
            books_of[member] = []
        if loan["book_id"] not in books_of[member]:
            books_of[member].append(loan["book_id"])
    pairs = {}
    for member in books_of:
        ids = sorted(books_of[member], key=int)
        for i in range(len(ids)):
            for j in range(i + 1, len(ids)):
                pair = ids[i] + "+" + ids[j]
                pairs[pair] = pairs.get(pair, 0) + 1
    best = ""
    for pair in pairs:
        if best == "" or pairs[pair] > pairs[best]:
            best = pair
    return best, pairs[best]
```

*The pair borrowed by the most members. code/grade-8/06-project-data-explorer/exercises/best_pair.py*

It returns `('5+47', 3)`: three members borrowed both books 5 and 47. Other pairs also reach 3; the [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) keeps the first one it meets. Sorting the numbers of each member’s books with `key=int` makes sure each pair is always written the same way, smaller number first.
