Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 8: Dictionaries and sets

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.

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.

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"] - 1

predict each value, without running anything:

  • d1: stock, as a dictionary

  • d2: len(stock)

  • d3: stock.get("figs", 0)

  • d4: "pears" in stock

  • d5: 7 in stock

  • d6: the kind of error that stock["figs"] raises, as a string

  • d7: list(stock)

  • d8: sum(stock.values())

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:

  1. word_counts(text) returns a dictionary from each word of text to the number of times it appears. Build it with a loop and get, not with Counter.

  2. top_words(text, n) returns the n most common words and their counts, as a list of (word, count) tuples. Use Counter and most_common.

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.

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.

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.

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 meeting

  • chen_latest: Chen’s latest rating, the last in Chen’s list

  • early_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.

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 days

  • either: the set of people who came on at least one day

  • monday_only: the set of people who came on Monday but not Tuesday

  • one_day_only: the set of people who came on exactly one of the days

  • distinct_monday: how many different people came on Monday

Exercise L8.6 (LO-8.3, ★★, about 10 minutes)

Write two functions:

  1. first_repeat(items) returns the first item that appears for a second time, or None if no item does: first_repeat(["a", "b", "c", "b", "a"]) is "b". Keep a set of the items seen so far.

  2. has_repeats(items) returns True if any item appears more than once. Write it in one line, with set and len.

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.

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.

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.

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.

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 guess

  • s2: a phone book, to find a person’s number from their name

  • s3: the moves of a game, in order, so the game can be replayed

  • s4: a square on a board, as its row and column, used as a key in a dictionary of pieces

  • s5: how many times each word appears in a book

  • s6: the email addresses on two mailing lists, to find the addresses on both

Write your six sentences here, in place of this line.

Summary

In this lab you:

  • looked up, counted, and grouped values with dictionaries, get, and Counter;

  • 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.