Step 1 of 8 · Reading · ~3 min
Learn
Dictionaries and Sets
Dictionary Fundamentals
A dict looks values up by a key you choose instead of by position. You will build one, read and change it without a KeyError, loop over it, nest dicts, and copy them safely.
The pairs you unpacked from enumerate and zip are exactly what a dict's .items() yields, and a dict copy is shallow in the same way a list copy was.
Building and reading
d[key] raises KeyError: 'screw' when the key is absent. d.get(key) gives None instead, and d.get(key, default) gives your default. in tests keys only, never values. A stored 0 is a present key, so test with in, not truthiness: if stock.get("washer"): is false for a count of 0.
Changing
Keys keep the order they were first inserted in (guaranteed since Python 3.7), and replacing a value does not move its key.
Looping, and the one thing you must not do
for k in d walks keys, d.values() walks values, d.items() walks (key, value) tuples, which you unpack in the for header. Adding or deleting keys while looping fails:
Loop over a snapshot, for item in list(stock):, and delete from the dict itself. Changing the values of existing keys mid-loop is safe.
What can be a key
A key must be hashable: Python files it under a number computed from its contents, which only works if the contents cannot change. Strings, numbers and tuples of those qualify; lists, sets and dicts do not.
Nesting, comprehensions, sorting
Values can be anything, including dicts and lists. A new key needs its inner list created first:
A dict comprehension is the comprehension you know with key: value in front: {k: v * 2 for k, v in stock.items() if v > 5} gives {'nut': 140}. For ordering, sorted(d) returns the sorted keys as a list, and sorted(d.items()) returns the sorted (key, value) tuples.:
Copies are shallow
d.copy() builds a new outer dict but shares every inner value; copy.deepcopy (from import copy) duplicates everything:
Common mistakes
- Bare
d[k]on a key that may not exist crashes withKeyErrorinstead of printing a fallback. Usegetorin. - Leaving an empty inner dict behind after removing its last entry. The outer key still exists, so a lookup prints an empty line instead of a "missing" message.
- Testing a value for truthiness. A stored 0 looks absent, so a course whose best score is 0 looks empty.
- Relying on insertion order for a tie. It is not alphabetical; sort the keys when the rule says so.
Your exercise
You maintain a gradebook as a dict of dicts, driven by commands read from input. The starter parses each command line; fill in the five commands. Check every lookup for an unknown student or course, and remove a student once the last course is gone.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…