Objectives: LO-8.1, LO-8.2, LO-8.3, LO-8.4
Prerequisites: the Module 8 reading and
Lab 7
Time: about 2 hours
In this lab you look up, count, and group values with dictionaries, read values from nested
data, combine sets, time lookups in a list and in a set and read the plot, and choose a data
structure for each of several tasks. As before, each exercise ends with a check cell that prints
passed or says what is wrong, and fails until you answer.
Setup¶
Run the next cell first. It imports timeit and Counter, and matplotlib, the plotting library
that setup.md installed, and prints the versions of Python and matplotlib.
import math
import sys
import timeit
from collections import Counter
import matplotlib
import matplotlib.pyplot as plt
print("Python", sys.version.split()[0])
print("matplotlib", matplotlib.__version__)1. Dictionaries¶
Run the next cell, then add pairs of your own, change a price, and look up a key that isn’t
there, first with get and then with square brackets.
prices = {"tea": 2.50, "coffee": 3.20, "cake": 4.00}
prices["juice"] = 2.80
print(prices)
print(prices.get("muffin", 0), "tea" in prices, 2.50 in prices)
for item, price in prices.items():
print(item, price)Exercise L8.1 (LO-8.1, ★, about 10 minutes)¶
After this code runs:
stock = {"apples": 4, "pears": 0}
stock["plums"] = 7
stock["apples"] = stock["apples"] - 1predict each value, without running anything:
d1:stock, as a dictionaryd2:len(stock)d3:stock.get("figs", 0)d4:"pears" in stockd5:7 in stockd6: the kind of error thatstock["figs"]raises, as a stringd7:list(stock)d8:sum(stock.values())
d1 = ...
d2 = ...
d3 = ...
d4 = ...
d5 = ...
d6 = "..."
d7 = ...
d8 = ...stock = {"apples": 4, "pears": 0}
stock["plums"] = 7
stock["apples"] = stock["apples"] - 1
assert d1 == stock, "d1: one key is added, and one value is replaced."
assert d2 == len(stock), "d2: len counts the pairs."
assert d3 == stock.get("figs", 0), "d3: get gives its default for a missing key."
assert d4 == ("pears" in stock), "d4: in asks about keys; a value of 0 doesn't matter."
assert d5 == (7 in stock), "d5: in looks at the keys, not the values."
assert d6 == "KeyError", "d6: what does a missing key in square brackets raise?"
assert d7 == list(stock), "d7: a list of the keys, in the order they were added."
assert d8 == sum(stock.values()), "d8: the total of the values."
print("passed")Exercise L8.2 (LO-8.1, ★★, about 15 minutes)¶
The next cell stores a notice written for this lab, and words_of, which returns its words in
lowercase without punctuation, as Lab 6 did. Run it. Then write two functions:
word_counts(text)returns a dictionary from each word oftextto the number of times it appears. Build it with a loop andget, not withCounter.top_words(text, n)returns thenmost common words and their counts, as a list of(word, count)tuples. UseCounterandmost_common.
NOTICE = """The library will close early on Friday. On Friday the reading room closes
at noon, and the library closes at two. The reading room opens again on Saturday."""
PUNCTUATION = '.,;:!?"()-'
def words_of(text):
"""Return the words of text in lowercase, without punctuation at either end."""
cleaned = [word.strip(PUNCTUATION).lower() for word in text.split()]
return [word for word in cleaned if word != ""]
print(words_of(NOTICE)[:8])def word_counts(text):
"""Return a dictionary from each word of text to how many times it appears."""
...counts = word_counts(NOTICE)
assert type(counts) is dict, "word_counts should build an ordinary dictionary, not a Counter."
assert counts["the"] == 4, f"the appears 4 times, not {counts.get('the')}."
assert counts["friday"] == 2 and counts["saturday"] == 1, "Count each word once per appearance."
assert len(counts) == 17, f"NOTICE has 17 different words, not {len(counts)}."
assert word_counts("") == {}, "No words give an empty dictionary."
assert top_words(NOTICE, 2) == [("the", 4), ("on", 3)], "top_words: the and on come first."
assert top_words(NOTICE, 3)[2] == ("library", 2), (
"Several words appear twice. most_common puts the one seen first, library, first."
)
print("passed")Several words appear twice, and most_common lists them in the order they first appear, not
alphabetically. Run the next cell to see them all.
print(top_words(NOTICE, 10))Exercise L8.3 (LO-8.1, ★★, about 15 minutes)¶
Write group_by_length(words), which returns a dictionary from each word length to a list of the
words of that length, each word once, in the order they first appear:
group_by_length(["tea", "milk", "cake", "tea", "jam", "juice"])returns {3: ['tea', 'jam'], 4: ['milk', 'cake'], 5: ['juice']}.
Hint
Follow the reading’s grouping pattern: give each new length an empty list, then append the word to its length’s list, but only if it isn’t in that list yet.
def group_by_length(words):
"""Return a dictionary from each length to the distinct words of that length, in order."""
...expected = {3: ["tea", "jam"], 4: ["milk", "cake"], 5: ["juice"]}
got = group_by_length(["tea", "milk", "cake", "tea", "jam", "juice"])
assert got == expected, f"Expected {expected}, but got {got}."
assert group_by_length([]) == {}, "No words give an empty dictionary."
groups = group_by_length(words_of(NOTICE))
assert groups[7] == ["library", "reading"], "Each word once, in the order first seen."
assert list(groups) == [3, 7, 4, 5, 2, 6, 8], "Lengths should appear in the order first seen."
print("passed")2. Nested data¶
CLUB describes a chess club made up for this lab. Run the cell, then read it: a dictionary
whose values include a list of dictionaries, each with a list inside.
CLUB = {
"name": "Riverside Chess Club",
"meetings": {"Tue": "18:00", "Sat": "10:00"},
"members": [
{"name": "Ana", "joined": 2021, "ratings": [1450, 1480, 1510]},
{"name": "Ben", "joined": 2023, "ratings": []},
{"name": "Chen", "joined": 2019, "ratings": [1610, 1590, 1650, 1700]},
{"name": "Dara", "joined": 2024, "ratings": [1300, 1350]},
],
}Exercise L8.4 (LO-8.2, ★★, about 15 minutes)¶
Write an expression that reads each value from CLUB, rather than typing the value itself:
saturday: the time of the Saturday meetingchen_latest: Chen’s latest rating, the last in Chen’s listearly_members: a list comprehension of the names of the members who joined before 2022
Then write latest_ratings(club), which returns a dictionary from each member’s name to their
latest rating, leaving out members who have no ratings yet.
saturday = ...
chen_latest = ...
early_members = ...
def latest_ratings(club):
"""Return a dictionary from each member's name to their latest rating, if they have one."""
...assert saturday == "10:00", "saturday: the meetings dictionary, then the key Sat."
assert chen_latest == 1700, "chen_latest: the members list, Chen's dictionary, its ratings, [-1]."
assert early_members == ["Ana", "Chen"], "early_members: the names of members with joined < 2022."
assert latest_ratings(CLUB) == {"Ana": 1510, "Chen": 1700, "Dara": 1350}, (
"latest_ratings: one pair for each member with ratings; Ben has none yet."
)
other = {"members": [{"name": "Eli", "joined": 2025, "ratings": [1200, 1250]}]}
assert latest_ratings(other) == {"Eli": 1250}, "latest_ratings should read the club it is given."
print("passed")3. Sets¶
Exercise L8.5 (LO-8.3, ★, about 10 minutes)¶
MONDAY and TUESDAY list who came to a club on each day, with repeats where someone signed in
twice. Using sets and set operators, set:
both: the set of people who came on both dayseither: the set of people who came on at least one daymonday_only: the set of people who came on Monday but not Tuesdayone_day_only: the set of people who came on exactly one of the daysdistinct_monday: how many different people came on Monday
MONDAY = ["Ana", "Ben", "Ana", "Chen", "Femi"]
TUESDAY = ["Chen", "Dara", "Ben", "Eli", "Chen"]both = ...
either = ...
monday_only = ...
one_day_only = ...
distinct_monday = ...for name, value in [("both", both), ("either", either), ("monday_only", monday_only),
("one_day_only", one_day_only)]:
assert type(value) is set, f"{name} should be a set, made with set() and an operator."
assert both == {"Ben", "Chen"}, "both: the intersection, &."
assert either == {"Ana", "Ben", "Chen", "Dara", "Eli", "Femi"}, "either: the union, |."
assert monday_only == {"Ana", "Femi"}, "monday_only: the difference, -."
assert one_day_only == {"Ana", "Dara", "Eli", "Femi"}, "one_day_only: the symmetric difference, ^."
assert distinct_monday == 4, "distinct_monday: Ana signed in twice."
print("passed")Exercise L8.6 (LO-8.3, ★★, about 10 minutes)¶
Write two functions:
first_repeat(items)returns the first item that appears for a second time, orNoneif no item does:first_repeat(["a", "b", "c", "b", "a"])is"b". Keep a set of the items seen so far.has_repeats(items)returnsTrueif any item appears more than once. Write it in one line, withsetandlen.
def first_repeat(items):
"""Return the first item that appears a second time, or None."""
...assert first_repeat(["a", "b", "c", "b", "a"]) == "b", "b is the first item seen a second time."
assert first_repeat([1, 2, 3]) is None, "With no repeats, return None."
assert first_repeat([]) is None, "With no items, return None."
assert first_repeat([7, 7]) == 7, "The second 7 is a repeat."
assert has_repeats([1, 2, 1]) is True and has_repeats([1, 2, 3]) is False, (
"has_repeats: compare the number of items with the number of distinct items."
)
assert has_repeats([]) is False, "No items have no repeats."
print("passed")4. Timing lookups¶
The next cell times looking up the last number in a list and in a set, for lists of 10,000 to 100,000 numbers. It looks up each one 200 times and works out the time for one lookup in microseconds (µs), millionths of a second. It takes about a second to run. It prints a table of the times, which the plot after it draws.
sizes = [10_000 * k for k in range(1, 11)]
list_us = []
set_us = []
for size in sizes:
numbers_list = list(range(size))
numbers_set = set(numbers_list)
last = size - 1
list_us.append(timeit.timeit(lambda: last in numbers_list, number=200) / 200 * 1_000_000)
set_us.append(timeit.timeit(lambda: last in numbers_set, number=200) / 200 * 1_000_000)
print(f"{'items':>8}{'list (µs)':>12}{'set (µs)':>12}")
for size, list_time, set_time in zip(sizes, list_us, set_us):
print(f"{size:>8,}{list_time:>12.1f}{set_time:>12.3f}")Run the next cell to draw the plot. The list’s times are blue circles and the set’s are orange squares, and each line is labeled at its right end.
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(sizes, list_us, color="#257de0", marker="o", markersize=6, linewidth=2, label="list")
ax.plot(sizes, set_us, color="#f47230", marker="s", markersize=6, linewidth=2, label="set")
for label, times in [("list", list_us), ("set", set_us)]:
ax.annotate(label, (sizes[-1], times[-1]), xytext=(8, 0), textcoords="offset points",
va="center", color="#333333")
ax.set_xlabel("Number of items")
ax.xaxis.set_major_formatter("{x:,.0f}")
ax.set_ylabel("Time for one lookup (µs)")
ax.set_title("Looking up the last item in a list and in a set")
ax.grid(color="#e6e6e6", linewidth=1)
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, loc="upper left")
plt.show()Exercise L8.7 (LO-8.4, ★★, about 10 minutes)¶
Read the plot and the table, then answer:
grows: which line climbs in proportion to the number of items,"list"or"set"?list_factor: with 1,000,000 numbers instead of 100,000, about how many times as long would one list lookup of the last number take? Give a whole number.set_factor: and about how many times as long would one set lookup take?average_fraction: the cell looks up the last number. If it looked up a number chosen at random from the list instead, about what fraction of this time would a list lookup take on average? Give a decimal.
grows = "..."
list_factor = ...
set_factor = ...
average_fraction = ...assert grows == "list", "grows: one line climbs; the other stays near zero."
assert list_factor == 10, "list_factor: the time grows in proportion to the number of items."
assert set_factor == 1, "set_factor: a set lookup takes about the same time at any size."
assert math.isclose(average_fraction, 0.5), (
"average_fraction: on average, how far into the list is a number chosen at random?"
)
print("passed")A set isn’t free to build. The next cell times building a set of 100,000 numbers, and divides by the time of one list lookup of the last number, from the table: how many lookups the set must save before building it pays off. Run it a few times; the number changes a little each time.
build_us = timeit.timeit(lambda: set(numbers_list), number=20) / 20 * 1_000_000
print(f"building the set: {build_us:,.0f} µs, about {build_us / list_us[-1]:.1f} list lookups")Exercise L8.8 (LO-8.4, ★★, about 10 minutes)¶
For each task, choose the data structure that suits it best, and set the variable to "list",
"tuple", "dict", or "set". Then, in the Markdown cell after the check, write one sentence
for each that names the operation the task needs most and why your choice makes it fast or
simple.
s1: the letters already guessed in a word game, checked after every guesss2: a phone book, to find a person’s number from their names3: the moves of a game, in order, so the game can be replayeds4: a square on a board, as its row and column, used as a key in a dictionary of piecess5: how many times each word appears in a books6: the email addresses on two mailing lists, to find the addresses on both
s1 = "..."
s2 = "..."
s3 = "..."
s4 = "..."
s5 = "..."
s6 = "..."assert s1 == "set", "s1: the operation is in, done after every guess."
assert s2 == "dict", "s2: find a value (the number) from a key (the name)."
assert s3 == "list", "s3: the order matters, and moves are added at the end."
assert s4 == "tuple", "s4: a fixed pair that must not change, because it is a key."
assert s5 == "dict", "s5: a count for each word: a dictionary or a Counter."
assert s6 == "set", "s6: the addresses on both lists are an intersection."
print("passed")Write your six sentences here, in place of this line.
Summary¶
In this lab you:
looked up, counted, and grouped values with dictionaries,
get, andCounter;read values from nested dictionaries and lists, and built a dictionary from them;
combined sets with
&,|,-, and^, and used a set to find repeats;timed lookups in a list and a set, and read from the plot how each grows with size; and
chose a data structure for a task by the operation it needs most.
Next, the Module 8 practice gives you more exercises with answers. After it come PA2, which brings Modules 6 to 8 together, and Self-test 1, on everything so far.