← All concepts

Lecture 2

Dictionaries

A dictionary is a lookup table: each key points to a value.

Looking things up

Square brackets with a key give its value; assigning to a new key adds it. Reading a key that is not there raises a KeyError — keys are case-sensitive.

codons = {"ATG": "M", "TGG": "W"}
codons["TTT"] = "F"
print(codons["ATG"], len(codons))

Output

M 3

.get() for missing keys

.get(key, default) returns the default instead of raising an error. That makes it the standard way to count.

counts = {}
for base in "GATTACA":
counts[base] = counts.get(base, 0) + 1
print(counts)
print(counts.get("N", 0))

Output

{'G': 1, 'A': 3, 'T': 2, 'C': 1}
0

Looping through a dictionary

.items() gives each key together with its value; .keys() and .values() give one side.

groups = {"ctrl": 4, "drug": 6}
for name, n in groups.items():
print(name, n)

Output

ctrl 4
drug 6

Going further

From the advanced notebook — this is what the advanced questions test.

Building and sorting

zip() pairs two lists, and dict() turns the pairs into a dictionary. sorted(d.items(), key=lambda kv: kv[1]) sorts the pairs by value; add reverse=True for largest first.

d = dict(zip(["rat", "bat", "cat"], [3, 7, 5]))
ranked = sorted(d.items(), key=lambda kv: kv[1], reverse=True)
print(ranked[0])

Output

('bat', 7)

Comprehensions and nesting

A dictionary comprehension builds key: value pairs in one line. A value can itself be a dictionary — look up twice.

squares = {n: n * n for n in [1, 2, 3]}
mice = {"m1": {"weight": 21}}
print(squares, mice["m1"]["weight"])

Output

{1: 1, 2: 4, 3: 9} 21