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}d[key]gives the value forkey. A key that isn’t there stops with an error that names it:prices["muffin"]isKeyError: 'muffin'.d[key] = valueadds the pair if the key is new, and replaces the value if it isn’t. Each key appears at most once.key in dasks whetherdhas the key. It looks only at keys:"tea" in pricesisTrue, but2.75 in pricesisFalse.del d[key]removes a pair, andd.pop(key)removes it and returns its value.{}is the empty dictionary, andlencounts its pairs.A dictionary keeps its keys in the order they were added; Python has promised that since version 3.7.
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.75keys() 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 0from collections import Counterimports one name from a module, so the code can writeCounterinstead ofcollections.Counter. Module 9 explains imports fully.Counter(words)counts the items of any sequence.A missing key counts as 0, rather than raising a
KeyError.most_common(n)returns thenmost common items and their counts, most common first, as a list of tuples. Items with equal counts come in the order they were first seen, not in alphabetical order.
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 2008Lists 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
34Read 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']
TrueWrite a set as values between curly braces.
{}is an empty dictionary, not an empty set; the empty set isset().A set has no order. Python may print its items in any order, and for strings the order can change from one run of the program to the next.
sorted(s)gives a list in order when you need one.set(items)makes a set from any sequence, solen(set(items))counts the distinct items, andsorted(set(items))lists them without repeats. To remove repeats but keep the original order,list(dict.fromkeys(items))works, because a dictionary keeps its keys in order.add(x)adds an item;remove(x)removes one, and stops with aKeyErrorif it isn’t there;discard(x)removes one if it is there.Items must be values that can’t change, as dictionary keys must.
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']| Operator | Name | Gives the items |
|---|---|---|
a & b | intersection | in both |
a | b | union | in either, or both |
a - b | difference | in a but not in b |
a ^ b | symmetric difference | in exactly one of them |
a <= b | subset | True 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.
A list or a tuple compares
xwith each item in turn, from the start, until one is equal. For a list of items that can take comparisons, so the time grows in proportion to : a list ten times as long takes about ten times as long to search.A set or a dictionary works out a number from
x, called its hash, and uses it to go straight to the one place wherexwould be stored. On average that takes the same time however many items there are.
People write these costs in big O notation, which describes how the time grows with the size and ignores constant factors: for the list, and 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 sThe 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 to | Use | Because |
|---|---|---|
| Keep items in order, add to the end, and go through them all | list | It keeps order, and append is fast |
| Reach the item at a position, or sort | list | Only sequences have positions |
| Store a fixed record, or a key made of several values | tuple | It 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 setting | dictionary | It finds a key without searching |
| Ask “have I seen this?” many times, or remove repeats | set | in 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¶
| Belief | What Python does | Example that breaks it |
|---|---|---|
d[key] gives None for a missing key | It stops with a KeyError; get gives None | prices["muffin"] is KeyError: 'muffin' |
in on a dictionary looks at the values | It looks at the keys | 2.75 in prices is False |
{} is an empty set | It is an empty dictionary | type({}) is dict; use set() |
| A set keeps items in the order they were added | A set has no order | {"b", "a"} may print in either order |
| Any value can be a key | Only values that can’t change | {[1, 2]: "x"} is a TypeError |
most_common breaks ties alphabetically | Ties keep the order first seen | Counter("bca").most_common() starts with b |
A list is as good as a set for in | A list compares item by item | 1,000 searches of 100,000 items: 0.6 s against 0.00004 s |
Summary¶
A dictionary maps keys to values.
d[key]reads a value and stops if the key is missing;getgives a default instead.inandforwork on its keys, anditems()gives its pairs.Count with
counts[x] = counts.get(x, 0) + 1, or withcollections.Counterand itsmost_common. Group with a dictionary of lists.Dictionaries and lists nest to any depth. Read nested data one step at a time, with an index for a list and a key for a dictionary.
A set holds distinct values without order.
set(items)removes repeats, and&,|,-, and^combine sets.inon a list or tuple takes time in proportion to its length; on a set or dictionary, about the same time at any size.timeitmeasures the difference. Choose a structure by the operations the task needs most.
Self-check¶
Answer each question before you open its answer.
After
stock = {"apples": 4}, what dostock.get("pears", 0),"apples" in stock,4 in stock, andstock["pears"]give?Answer
0,True,False(becauseinlooks at keys), andKeyError: 'pears'.Write a loop that counts how many times each letter appears in
"banana", with a dictionary andget.Answer
counts = {} for letter in "banana": counts[letter] = counts.get(letter, 0) + 1countsis{'b': 1, 'a': 3, 'n': 2}.Counter("banana")gives the same counts.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.What are
sorted(set("banana") & set("bandana"))andsorted(set("bandana") - set("banana"))?Answer
['a', 'b', 'n']and['d']. A set of a string’s letters has no repeats.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¶
The Python Tutorial, sections 5.4, Sets, 5.5, Dictionaries, and 5.6, Looping Techniques. Sets, dictionaries, and
items(), in the language’s own words.The Python Standard Library,
collections.Counterandtimeit. Everything aCountercan do, and how to time code from a program or from the command line.Time complexity of operations on built-in types, in the Python 3.15 documentation. The cost of each operation on lists, sets, and dictionaries.
Allen B. Downey, Think Python, 3rd edition, chapter 10, Dictionaries. Dictionaries, counting with them, and looping over them.
Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 7, Dictionaries and Structuring Data.
get,setdefault, and nested dictionaries and lists, with programs that model real things.