PYTH-4

Dicts, sets and tuples

Python for DSALesson 4 of 614 min

A list finds a value by its position. A dictionary finds a value by a key, such as a name or a code, and it does this without searching through the other keys. Many practice problems in this course depend on this fact.

Dictionaries

A dictionary (dict) stores pairs. Each pair has a key and a value. You look up a value by its key, the way you look up a word in a real dictionary to find its meaning.

platform = {"BCT": 3, "HWH": 9}
platform["BCT"]            # 3
platform["MAS"] = 5        # add a new pair
"HWH" in platform          # True: is "HWH" a key?
platform.get("NDLS", 0)    # 0: the key is missing, so use the default
for code, p in platform.items():
    print(code, p)

Reading a missing key with square brackets, as in platform["NDLS"], raises a KeyError. Use in or .get when a key might be missing. A key must be a value that cannot change, such as a number, a string or a tuple. A list cannot be a key.

Counting with a dictionary

Counting how often each value appears is one of the most common jobs in this course. Step through the figure to see it done with .get.

FIG PYTH-4.1Counting station codes with a dictionary
BCT
HWH
BCT
MAS
HWH
BCT
codes = ["BCT", "HWH", "BCT", "MAS", "HWH", "BCT"]
counts = {}
for c in codes:
    counts[c] = counts.get(c, 0) + 1
print(counts)
counts: key
counts: keyValue
none yet
Printed
 
1/15

We want to know how often each station code appears.

Step 1 of 15

Python also has a ready-made counter. Counter from the collections module does the same thing in one line:

from collections import Counter
Counter(["BCT", "HWH", "BCT"])     # Counter({'BCT': 2, 'HWH': 1})

Sets

A set holds values with no repeats and no order. Its main use is a fast answer to one question: is this value in the set?

seen = set()          # an empty set ({} would make an empty dict)
seen.add("BCT")
seen.add("BCT")       # already there, so nothing changes
"BCT" in seen         # True
len(seen)             # 1
set([3, 1, 3, 2])     # {1, 2, 3}: repeats removed

A set has no index. seen[0] is an error, because the values have no positions.

Tuples

A tuple is like a list that cannot be changed. You write it with round brackets. Use a tuple for a small group of values that belong together, such as a row and a column.

cell = (2, 5)
row, col = cell       # unpacking: row = 2, col = 5
visited = {(0, 0), (2, 5)}    # tuples can go in a set
a, b = b, a           # swap two names; Python builds a tuple to do it

How fast each one is

This table is the reason dictionaries and sets matter. Here n is the number of values stored. “Average” means typical behaviour; the HASH station explains the rare slow case.

Cost of common operations
Operationlistdict or set (average)
x in c (c is the list, dict or set)checks values one by one, up to nabout the same time for any n
add a valueappend: fastadd or d[k] = v: fast
remove a valueup to n movesfast
read by positiona[i]: fastnot possible

PYTH-4 counts as completed once you step through the figure to the last step.