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.

Module 8: Dictionaries and sets

Objectives: LO-8.1, LO-8.2, LO-8.3, LO-8.4
Prerequisites: Module 7
Time: about 5.5 hours: 2 for this reading, 2 for Lab 8, and 1.5 for the practice

A list finds a value by its position. Often you want to find a value by a name instead: the count of a word, the price of an item, the phone number of a person. A dictionary stores pairs of a key and a value, and finds the value for a key without searching. A set stores values without order and without repeats, and answers “is this one of them?” without searching either. This module uses both, then measures how much faster they are than a list, and shows when that matters.

Dictionaries

Write a dictionary as key: value pairs between curly braces:

prices = {"tea": 2.50, "coffee": 3.20, "cake": 4.00}
print(prices["coffee"])
prices["juice"] = 2.80
prices["tea"] = 2.75
print(len(prices), prices)
3.2
4 {'tea': 2.75, 'coffee': 3.2, 'cake': 4.0, 'juice': 2.8}

Keys must be values that can’t change: strings, numbers, and tuples of them. A list as a key stops with TypeError: unhashable type: 'list', which Python 3.15 words as cannot use 'list' as a dict key (unhashable type: 'list'). The last section explains why. Values can be anything, lists and other dictionaries included.

get: a default for a missing key

d.get(key) returns the value for key, or None if it isn’t there, instead of stopping. d.get(key, default) returns default instead of None: prices.get("muffin", 0) is 0. Use get when a missing key is normal, and d[key] when a missing key means something has gone wrong, so the error tells you at once.

Looping over a dictionary

A for loop over a dictionary gives its keys. items() gives its pairs, as tuples, so the loop can unpack them:

for item, price in prices.items():
    print(f"{item:<8}{price:>6.2f}")
print(f"Total   {sum(prices.values()):>6.2f}")
tea       2.75
coffee    3.20
cake      4.00
juice     2.80
Total    12.75

keys() and values() give the keys and the values alone. sorted(prices) is a list of the keys in order, and sorted(prices.items(), key=lambda pair: pair[1]) is a list of the pairs in order of value, with Module 7’s sorting by key.

Don’t add or remove keys while a loop goes through the same dictionary: Python stops with RuntimeError: dictionary changed size during iteration. Loop over list(d), a copy of the keys, instead, or build a new dictionary.

Counting and grouping

Counting with a dictionary

To count how often each value appears, keep a dictionary from each value to its count:

words = "the cat and the dog and the bird".split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)
{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}

counts.get(word, 0) is the count so far, or 0 the first time a word appears. It replaces an if that would check whether the key is there.

collections.Counter

Counting is common enough that the standard library does it for you. Counter, from the collections module, is a kind of dictionary built for counting:

from collections import Counter

counts = Counter(words)
print(counts.most_common(2))
print(counts["the"], counts["fish"])
[('the', 3), ('and', 2)]
3 0

Grouping

To group values, map each group’s key to a list of the values in it:

fruits = ["apple", "fig", "avocado", "banana", "cherry", "blueberry"]
by_letter = {}
for fruit in fruits:
    first = fruit[0]
    if first not in by_letter:
        by_letter[first] = []
    by_letter[first].append(fruit)
print(by_letter)
{'a': ['apple', 'avocado'], 'f': ['fig'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

The first time a letter appears, the loop gives it an empty list; every time, it appends the fruit to that letter’s list. by_letter[first].append(fruit) changes the list that the dictionary holds, as Module 7’s aliasing would predict. The standard library has shorter forms of the same pattern, by_letter.setdefault(first, []).append(fruit) and collections.defaultdict(list); the loop above is the clearest.

Records and nested data

A dictionary makes a good record, because it names each field: book["year"] says what it reads, where Module 7’s tuple record needed book[2].

book = {"title": "Lanterns", "author": "Nakamura", "year": 2008}
print(book["title"], book["year"])
Lanterns 2008

Lists and dictionaries can hold each other, to any depth. This is nested data:

library = {
    "name": "Riverside Library",
    "hours": {"Mon": "9-17", "Sat": "10-16"},
    "books": [
        {"title": "Lanterns", "year": 2008, "loans": [3, 5, 4]},
        {"title": "River Notes", "year": 2019, "loans": [10, 12]},
    ],
}
print(library["hours"]["Sat"])
print(library["books"][1]["title"])
print(library["books"][0]["loans"][-1])
print(sum([sum(book["loans"]) for book in library["books"]]))
10-16
River Notes
4
34

Read a long expression one step at a time, from the left. library["books"] is a list; [1] is its second item, a dictionary; ["title"] is that dictionary’s title. When a step fails, print the value before it and its type, with print(type(value), value), and check which kind of brackets it needs: an index for a list, a key for a dictionary.

This shape, dictionaries and lists inside each other, is the shape of JSON, the format most web services use, which Module 11 reads and writes. A field that some records have and others don’t is common in such data; book.get("subtitle", "") reads it without stopping.

Dictionaries are mutable, like lists, so Module 7’s rules about aliasing and copies apply to them too. d.copy() is a shallow copy, and two names can refer to one dictionary.

Sets

A set holds values without order and without repeats:

drinks = {"tea", "coffee", "tea", "juice"}
print(len(drinks), sorted(drinks))
print("tea" in drinks)
3 ['coffee', 'juice', 'tea']
True

Set operations

Sets combine with operators that work like the diagrams of sets in mathematics:

chess = {"Ana", "Ben", "Chen", "Dara"}
music = {"Chen", "Eli", "Ana"}
print(sorted(chess & music))
print(sorted(chess | music))
print(sorted(chess - music))
print(sorted(chess ^ music))
['Ana', 'Chen']
['Ana', 'Ben', 'Chen', 'Dara', 'Eli']
['Ben', 'Dara']
['Ben', 'Dara', 'Eli']
OperatorNameGives the items
a & bintersectionin both
a | bunionin either, or both
a - bdifferencein a but not in b
a ^ bsymmetric differencein exactly one of them
a <= bsubsetTrue if every item of a is in b

Choosing a data structure, and what it costs

How in works

The four collections answer x in collection in two very different ways.

People write these costs in big O notation, which describes how the time grows with the size nn and ignores constant factors: O(n)O(n) for the list, and O(1)O(1) on average for the set. The hash is also why keys and set items can’t change: a changed value would have a different hash, and would be filed in the wrong place. Python’s documentation lists these costs for every operation in Time complexity of operations on built-in types, a page of the Python 3.15 documentation that has no version for Python 3.12.

Measuring with timeit

timeit.timeit runs a piece of code many times and returns the total time in seconds. Give it a function to run, here a lambda (Module 7), and number, how many times to run it:

import timeit

numbers_list = list(range(100_000))
numbers_set = set(numbers_list)
list_time = timeit.timeit(lambda: 99_999 in numbers_list, number=1_000)
set_time = timeit.timeit(lambda: 99_999 in numbers_set, number=1_000)
print(f"list: {list_time:.4f} s, set: {set_time:.6f} s")

Python ignores underscores in numbers, so 100_000 is 100,000, written so it is easier to read. The code looks up the last number, the worst case for the list, 1,000 times in each collection. On a laptop with an Intel Core i7-11800H processor, running Linux and Python 3.12.3, three runs printed:

list: 0.6386 s, set: 0.000042 s
list: 0.6654 s, set: 0.000043 s
list: 0.6118 s, set: 0.000039 s

The set was about 15,000 times as fast. Your numbers will differ, because they depend on the computer and on what else it is doing, so run a measurement several times, and compare measurements only from the same computer.

Building the set isn’t free: set(numbers_list) took about 0.0017 s here, as long as about three searches of the list. To look up one value once, keep the list. To look up many values, build the set once and use it for every lookup. Lab 8 measures searches for many sizes, and plots how the time grows.

Choosing

Choose a data structure by the operations the task does most, and what each costs:

The task needs toUseBecause
Keep items in order, add to the end, and go through them alllistIt keeps order, and append is fast
Reach the item at a position, or sortlistOnly sequences have positions
Store a fixed record, or a key made of several valuestupleIt can’t change, so it can be a key or a set item
Look up a value by a key: a count, a price, a settingdictionaryIt finds a key without searching
Ask “have I seen this?” many times, or remove repeatssetin doesn’t search, and it has no repeats

Some list operations are slow for the same reason in is. insert(0, x) and pop(0) move every other item along one place, so they take time in proportion to the list’s length, while append and pop() at the end don’t. A program that takes items from the front of a long list many times can use collections.deque, a sequence built to add and remove at both ends quickly.

Common misconceptions

BeliefWhat Python doesExample that breaks it
d[key] gives None for a missing keyIt stops with a KeyError; get gives Noneprices["muffin"] is KeyError: 'muffin'
in on a dictionary looks at the valuesIt looks at the keys2.75 in prices is False
{} is an empty setIt is an empty dictionarytype({}) is dict; use set()
A set keeps items in the order they were addedA set has no order{"b", "a"} may print in either order
Any value can be a keyOnly values that can’t change{[1, 2]: "x"} is a TypeError
most_common breaks ties alphabeticallyTies keep the order first seenCounter("bca").most_common() starts with b
A list is as good as a set for inA list compares item by item1,000 searches of 100,000 items: 0.6 s against 0.00004 s

Summary

Self-check

Answer each question before you open its answer.

  1. After stock = {"apples": 4}, what do stock.get("pears", 0), "apples" in stock, 4 in stock, and stock["pears"] give?

    Answer

    0, True, False (because in looks at keys), and KeyError: 'pears'.

  2. Write a loop that counts how many times each letter appears in "banana", with a dictionary and get.

    Answer

    counts = {}
    for letter in "banana":
        counts[letter] = counts.get(letter, 0) + 1

    counts is {'b': 1, 'a': 3, 'n': 2}. Counter("banana") gives the same counts.

  3. Given data = {"rooms": [{"name": "Hall", "seats": 120}, {"name": "Lab", "seats": 24}]}, write an expression for the number of seats in the Lab.

    Answer

    data["rooms"][1]["seats"], which is 24: the list of rooms, its second item, and that dictionary’s seats.

  4. What are sorted(set("banana") & set("bandana")) and sorted(set("bandana") - set("banana"))?

    Answer

    ['a', 'b', 'n'] and ['d']. A set of a string’s letters has no repeats.

  5. A program checks each of 10,000 new usernames against a collection of 50,000 names already taken. Should the taken names be a list or a set, and why?

    Answer

    A set. With a list, each check compares the new name with up to 50,000 names, so the program can make up to 500 million comparisons. With a set, each check takes about the same short time whatever its size, and building the set once costs about as much as a few searches of the list.

Further reading