Course outline · 0% complete

0/32 lessons0%

Course overview →

Dictionaries: Looking Things Up by Name

lesson 7-1 · ~12 min · 21/32

Quiz

Warm-up from lesson 6-2: which list method adds an item to the END of a list?

A dict maps keys to values

Almost every record a real program touches is key-value shaped: a user profile (name, email, plan), a settings file, the JSON that every web service sends and receives. The dictionary is Python's container for that shape, and after the list it is the type you will use most for the rest of your career.

A list answers what is at position 2? A dictionary answers what is Ada's age? It stores key: value pairs in curly braces:

ages = {"Ada": 36, "Grace": 45}
OperationExampleResult
look upages["Ada"]36
add or replaceages["Alan"] = 41new pair stored
key exists?"Grace" in agesTrue
safe look upages.get("Linus", 0)0, no crash
sizelen(ages)number of pairs

Looking up a key that is not there with brackets stops the program with a KeyError. .get(key, default) returns the default instead, which is why it powers the counting pattern you are about to write.

Code exercise · python

Run this and match each line to the table. The `.get` on the last line asks for a missing key and survives.

Quiz

`ages` is `{"Ada": 36}`. What happens when the program runs `ages["Linus"]`?

"Ada""Grace""Alan"364541keysvalues
A dictionary is a set of arrows from unique keys to their values. Lookup follows the arrow.

Code exercise · python

Your turn: the counting pattern, dict edition. Count how many times each letter appears in `banana` using `counts.get(ch, 0) + 1`, then print the dict.