Skip to content

Unit 5 Review: Questions

Quiz 5 is on Wed Nov 18 (MWF sections) / Thu Nov 19 (TuTh sections). It is a paper quiz: no computer, no notes, no AI. It focuses on Weeks 11 and 12, but it builds on everything since Week 2, and it may include one short question about reading a text file (Week 10).

What you should be able to do (from the learning objectives):

  • Use a dictionary to look up a value by its key, and explain how that differs from checking membership in a set.
  • Use dictionary methods (get(), keys(), values(), items()) and loop over a dictionary to group and summarize data.
  • Read and write basic list, set, and dictionary comprehensions.
  • Navigate nested data (lists of lists, lists of dictionaries, dictionaries of lists), including data read from CSV and JSON files.
  • Given a description of how data is shaped, write code that pulls out or computes a result.

How to use this review. Work each section on paper first, the way you will on the quiz, and then check your answers (your instructor can give you the copy with answers shown). You are encouraged to use AI to study. Section 8 has prompts that make AI quiz you instead of doing the work for you. If you can only get an answer right after AI explains it, write a new question like it and try again tomorrow.


1. Looking things up in a dictionary (Week 11)

stock = {"apple": 12, "pear": 0, "plum": 5}

1.1 Write the type and value of each expression. If it causes an error, write the kind of error.

Expression Type Value
stock["plum"] int 5
stock.get("kiwi") NoneType None
stock.get("kiwi", 0) int 0
stock["kiwi"] KeyError Error
"pear" in stock bool True
12 in stock bool False (in checks keys, not values)
list(stock.keys()) list ["apple", "pear", "plum"]
sum(stock.values()) int 17
len(stock.items()) int 3
stock["pear"] or "sold out" str "sold out" (0 is falsy, Week 4)

1.2 Write one statement for each description. Start fresh from the original stock each time.

a. Add "kiwi" with a count of 8.   stock["kiwi"] = 8

b. Remove "pear" from the dictionary.   del stock["pear"]  or  stock.pop("pear")

c. Add 3 to the count of apples.   stock["apple"] += 3

d. Print the count of "mango", or 0 if there is no "mango" key, without causing an error.   print(stock.get("mango", 0))

1.3 A set fruits = {"apple", "pear"} and the dictionary stock can both answer "apple" in .... In one sentence, what can the dictionary tell you that the set cannot?

The dictionary can also retrieve data associated with the key (how many apples there are); the set can only say whether "apple" is present.


2. Looping over a dictionary (Week 11)

2.1 What is printed?

temps = {"Mon": 61, "Tue": 48, "Wed": 55, "Thu": 48}
coldest = None
for day, t in temps.items():
    if coldest is None or t < temps[coldest]:
        coldest = day
print(coldest)

Tue. Thursday ties at 48, but < is strict, so Tuesday is never replaced. With <= the answer would be Thu.

2.2 What is printed? (Each print ends with a space, so the output is on one line.)

team = {"Ava": 12, "Ben": 7, "Cy": 15}
for key in team:
    print(key, end=" ")
for value in team.values():
    if value > 10:
        print(value, end=" ")

Ava Ben Cy 12 15

2.3 Write the function. Use a loop over the list and a dictionary.

def group_by_length(words: list[str]) -> dict[int, list[str]]:
    """Group words by how many letters they have.

    Example: group_by_length(["hi", "cat", "ox", "dog"]) returns
    {2: ["hi", "ox"], 3: ["cat", "dog"]}
    """
    groups = {}
    for word in words:
        size = len(word)
        if size not in groups:
            groups[size] = []
        groups[size].append(word)
    return groups

2.4 Write the function. It is a two-step job: count first, then filter.

def repeats(votes: list[str]) -> list[str]:
    """Return the choices that got more than one vote, in the order
    they first appear.

    Example: repeats(["red", "blue", "red", "green", "red", "blue"])
    returns ["red", "blue"]
    """
    counts = {}
    for v in votes:
        counts[v] = counts.get(v, 0) + 1
    result = []
    for choice, n in counts.items():
        if n > 1:
            result.append(choice)
    return result

3. Comprehensions (Week 11)

3.1 Write the value of each comprehension.

Comprehension Value
[len(w) for w in ["to", "be", "or", "not"]] [2, 2, 2, 3]
[x for x in [5, -2, 0, 8, -1] if x > 0] [5, 8]
{c.lower() for c in "Mississippi"} {"m", "i", "s", "p"} (any order)
{n: n * n for n in range(1, 4)} {1: 1, 2: 4, 3: 9}
{k: v for k, v in [("Al", 9), ("Bo", 6)] if v > 7} {"Al": 9}
[s.strip() for s in " a , b,c ".split(",")] ["a", "b", "c"]

3.2 Rewrite as one line with a comprehension.

initials = []
for name in names:
    if name[0].isupper():
        initials.append(name[0])

initials = [name[0] for name in names if name[0].isupper()]

3.3 Rewrite as one line with a dictionary comprehension.

doubled = {}
for item, price in prices.items():
    doubled[item] = price * 2

doubled = {item: price * 2 for item, price in prices.items()}

3.4 Rewrite this comprehension as a loop.

evens = {n for n in nums if n % 2 == 0}
evens = set()
for n in nums:
    if n % 2 == 0:
        evens.add(n)

3.5 In one sentence, when is a regular loop clearer than a comprehension?

When the loop does more than filter and transform: several steps per item, printing, updating more than one variable, or logic too long to read on one line.


4. Lists of lists and nested loops (Week 12)

grid = [
    [3, 8, 1],
    [6, 2, 9],
    [4, 7, 5],
]

4.1 Write the value of each expression.

Expression Value
grid[1] [6, 2, 9]
grid[2][0] 4
grid[-1][-1] 5
len(grid) 3
len(grid[0]) 3
grid[0][1] + grid[1][0] 14
[row[1] for row in grid] [8, 2, 7] (the middle column)

4.2 What is printed?

total = 0
for row in grid:
    for value in row:
        if value % 2 == 0:
            total += value
print(total)

20 (8 + 6 + 2 + 4)

4.3 How many times does the inner print run, and what is printed? Write each line of output on its own line.

for i in range(3):
    for j in range(i + 1):
        print(j, end=" ")
    print()

6 times.

0
0 1
0 1 2

4.4 If a grid has r rows and c columns, how many times does the body of the inner loop run when you visit every cell?   r * c

4.5 Write the function. You need the index of each column, so loop over range(...) rather than over the values.

def column_sums(grid: list[list[int]]) -> list[int]:
    """Return the sum of each column. Assume every row has the same
    length and there is at least one row.

    Example: column_sums([[3, 8, 1], [6, 2, 9], [4, 7, 5]]) returns
    [13, 17, 15]
    """
    sums = []
    for c in range(len(grid[0])):
        total = 0
        for r in range(len(grid)):
            total += grid[r][c]
        sums.append(total)
    return sums

4.6 Write the function.

def find(grid: list[list[int]], target: int) -> tuple[int, int] | None:
    """Return the (row, column) of the first cell equal to target,
    searching row by row. Return None if target is not in the grid.

    Example: find([[3, 8, 1], [6, 2, 9]], 9) returns (1, 2)
    """
    for r in range(len(grid)):
        for c in range(len(grid[r])):
            if grid[r][c] == target:
                return (r, c)
    return None

5. Lists of dictionaries and dictionaries of lists (Week 12)

library = {
    "fiction": [
        {"title": "Dune", "year": 1965, "out": True},
        {"title": "Kindred", "year": 1979, "out": False},
    ],
    "science": [
        {"title": "Cosmos", "year": 1980, "out": True},
    ],
}

5.1 Describe the shape of library in one sentence, from the outside in.

A dictionary that maps each genre (a string) to a list of books, where each book is a dictionary with "title", "year", and "out" keys.

5.2 Write the type and value of each expression, or the kind of error.

Expression Type Value
library["science"][0]["title"] str "Cosmos"
len(library["fiction"]) int 2
library["fiction"][1]["year"] + 1 int 1980
list(library) list ["fiction", "science"]
library["fiction"][0]["title"][-1] str "e"
library["fiction"]["Dune"] TypeError Error (a list needs an int index)
library["poetry"] KeyError Error
library["science"][1] IndexError Error

5.3 Write one statement that adds this book to the "science" list: title "Silent Spring", year 1962, not checked out.

library["science"].append({"title": "Silent Spring", "year": 1962, "out": False})

5.4 Write one statement that marks Kindred as checked out.   library["fiction"][1]["out"] = True

5.5 Write the function. You'll need a loop inside a loop.

def checked_out(library: dict[str, list[dict]]) -> list[str]:
    """Return the titles of every book that is checked out, in any genre.

    Example: for the library above, returns ["Dune", "Cosmos"]
    """
    titles = []
    for books in library.values():
        for book in books:
            if book["out"]:
                titles.append(book["title"])
    return titles

5.6 Write the function. This time the genre is given, so you need only one loop.

def older_than(library: dict[str, list[dict]], genre: str, year: int) -> list[str]:
    """Return the titles in one genre published before the given year.
    Return an empty list if the genre is not in the library.

    Example: older_than(library, "fiction", 1970) returns ["Dune"]
    """
    return [b["title"] for b in library.get(genre, []) if b["year"] < year]

6. Reading and writing data files (Weeks 10 and 12)

6.1 Each line of grades.txt holds a name and a score separated by a space, like Ana 92. Fill in the blanks so that scores maps each name to its score as an int.

scores = {}
with open(____(1)____) as file:
    for line in file:
        name, score = ____(2)____
        scores[name] = ____(3)____

(1) "grades.txt"   (2) line.split()   (3) int(score)

6.2 Fill in the blanks so that each name and score is written on its own line of report.txt, like Ana: 92.

with open("report.txt", ____(1)____) as out:
    for name, score in ____(2)____:
        out.write(____(3)____)

(1) "w"   (2) scores.items()   (3) f"{name}: {score}\n"

6.3 What is the difference between opening a file with "w" and with "a"?

"w" erases the file (or creates it) and writes from the start; "a" keeps what is already there and adds to the end.

6.4 Why does each written line need "\n", but each line you read usually needs strip()?

write() does not add a newline for you, so you add it. When reading, each line still ends with its "\n", so strip() removes it before you split or compare.

6.5 trails.json holds a list of dictionaries. Fill in the blank to load it.

import json

with open("trails.json") as file:
    trails = ________________

json.load(file)

6.6 A CSV file has the header name,team,points. After you split(",") one line into parts, which expression gives the points as a number?   int(parts[2])


7. Cumulative review (Weeks 2–10)

The quiz builds on earlier weeks. These are quick checks; if any of them feel shaky, revisit that week's objectives.

7.1 Write the type and value of each expression.

Expression Type Value
7 // 2 * 2.0 float 6.0
"ab" * 2 + "c" str "ababc"
"Dukes"[1:4] str "uke"
not [] bool True
"a,b,,c".split(",") list ["a", "b", "", "c"]
" Hi ".strip().lower() str "hi"
10 % 4 == 2 and 3 > 5 bool False
len(set("banana")) int 3
"-".join(["a", "b", "c"]) str "a-b-c"

7.2 What is printed? (Week 10: changing a list inside a function.)

def add_bonus(scores):
    scores.append(5)
    scores = [0]
    return scores

mine = [9, 7]
result = add_bonus(mine)
print(mine, result)

[9, 7, 5] [0]. The append changes the caller's list; the assignment only makes the local name point to a new list.

7.3 For each job, would you use a for loop or a while loop? Give a one-phrase reason.

a. Add up every number in a list.   for: you know how many items there are.

b. Keep asking for a password until the user types one that is long enough.   while: you don't know how many tries it will take.

c. Look at every key in a dictionary.   for: the dictionary has a known set of keys.

d. Roll a die until it shows 6.   while: the number of rolls is random.

7.4 word = "cat". Does word.upper() change word? What would you write to keep the result?   No, strings are immutable, so upper() returns a new string. Write word = word.upper().


8. Studying with AI

Ask AI to quiz you, not to answer for you. For example:

  • "Give me a nested dictionary of about 10 lines and six expressions to evaluate on paper. Don't show the answers until I send mine."
  • "Here is my answer to a nested-loop trace and the right answer. Don't fix it for me; ask me questions until I find my own mistake."
  • "Describe the shape of some JSON data in words, and ask me to write a function that filters it. Then review my code like a strict grader."

Then close the chat and try one more problem by hand. That last problem is the honest measure of what you know.