Lecture 2
A dictionary is a lookup table: each key points to a value.
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(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) + 1print(counts)print(counts.get("N", 0))Output
{'G': 1, 'A': 3, 'T': 2, 'C': 1}
0.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
From the advanced notebook — this is what the advanced questions test.
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)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