Dictionaries
Store, look up, add, update and loop over key-value pairs in a dictionary, count words with one, and say which keys a dictionary accepts.
It opens on
stock = {"apple": 3, "pear": 5} holds a count for each fruit. What does stock["plum"] do: give 0, give None, or stop with an error?
Why it matters
Looking something up by name, a price by item, a grade by student, a count by word, is what most real data is, and a dictionary does it without searching a list; its two classic bugs are asking for a missing key and using a key that cannot be one.
Good to know first
- Lists: indexing and mutation: a list is read and changed by index
- Tuples and unpacking: for k, v in pairs takes a pair apart
- String methods and immutability: s.split() cuts a sentence into words
Step by step
Look up by key
Read a value with d[key], predict the KeyError for a missing key, and use get with a default and in to avoid it.
stock["pear"] asks for the value under the key "pear", and the run printed 5. The same pairs are a table of keys and values.
the same pairs as a table
A common mix-up
A missing key gives 0 or None like a failed search.
In fact: d[key] raises KeyError; only get returns a default.
Add, update and loop
Add a pair and update a value with d[key] = value, loop over the pairs, and say in what order they come.
Line 2 uses "plum", which is not a key, so a pair is added and stock has three pairs.
the first two rows
A common mix-up
Assigning to an existing key adds a second pair, or fails.
In fact: Keys are unique; the assignment replaces the old value.
Count words
Count how many times each word occurs in a sentence with a dictionary, and avoid the KeyError of a first occurrence.
The first word, the, is new, so get gives 0 and counts["the"] becomes 1. The words cat and and are new too, and each becomes 1.
A common mix-up
Counts[w] = counts[w] + 1 starts a new word at 1.
In fact: It reads counts[w] first, so a new word raises KeyError; use get with 0 or test with in.
Which keys are allowed
Say which values can be keys, read the TypeError for a list key, tell {} from an empty set, and say why a dictionary lookup is fast.
print(type({})) showed <class 'dict'>, so empty curly braces make an empty dictionary and not an empty set. An empty set is written set(). Sets are the next lesson.
A common mix-up
Any value can be a key, as any value can be in a list.
In fact: a key must be hashable, so a list or another dictionary cannot be one.
Try it
With scores = {"Ana": 8, "Raj": 6}, what is scores["Raj"] + scores.get("Mei", 1)?Answer
7
Hint: "Mei" is not a key, so get gives its default
With d = {"x": 1}, then d["y"] = 2 and d["x"] = 5, what does print(d) show?Answer
{'x': 5, 'y': 2}
Hint: x is old, y is new
What does counting the letters of "noon" give, in the order the keys appear?Answer
{'n': 2, 'o': 2}
Hint: n comes first, then o, then o and n
Can (2, 5) be a key of a dictionary, and can [2, 5]?Answer
(2, 5) yes; [2, 5] no, it is a list
Hint: Can the value change?
What does stock["apple"] + stock["pear"] give?Answer
8, since 3 + 5.
