Dictionaries
Last updated
A list finds things by position. A dictionary finds them by name: look up a title and get how many copies are on the shelf. In this lesson you'll make dictionaries, read, add and change values, read the error you get for a key that isn't there, loop over keys and values, count things, and keep dictionaries inside dictionaries.
By the end of this lesson you can
- Make a dictionary, and read, add, change and remove values by key
- Read a
KeyError, and avoid it withinor.get()with a default - Loop over a dictionary with
.items(), and use one to count things - Read and change values in dictionaries and lists kept inside a dictionary
Look things up by name
A dictionary, or dict, holds pairs: a key and its value. It's written in curly brackets, with a colon between each key and its value and commas between the pairs. Here the keys are "title", "author" and "year".
Put a key in square brackets to get its value. Where a list asks "what's at position 0?", a dict asks "what's stored under "title"?"
len() counts the pairs. A dict keeps its pairs in the order they were added. Keys are usually text or numbers, and each key appears only once.
Add, change and remove
copies["Emma"] = 0 changes the value under a key that's there already. Give a value to a key that isn't there, like "Beloved" on line 3, and the pair is added. del takes a pair out.
in asks whether a dict has a key. .get() looks up a key like square brackets do, but if the key isn't there it gives back None, or the default you pass it, instead of stopping.
Watch it run and see copies change in the table after each line.
A key that isn't there
Nobody has added Matilda to this dict. Press Run and read the error.
KeyError: 'Matilda'. Square brackets promise the key is there, and when it isn't, Python stops and names the key it couldn't find. Two fixes, depending on what the program should do:
- Ask first:
if title in copies:and only then readcopies[title]. - Use a default:
copies.get(title, 0)gives0for a title that isn't there.
Change line 3 to use copies.get(title, 0) and run it again.
Each key and value: .items()
A for loop over a dict gives you its keys, one each round (lines 2 and 3). To get the key and the value together, loop over .items(): each round gives a pair, which is unpacked into two names, like the tuples in lesson 1.9.
.keys() and .values() give just one side. Line 7 adds up all the values with sum().
Counting with a dictionary
A dict is the usual way to count things. This program counts how many loans each member has. The first time a name comes up, .get(member, 0) gives 0, so the count starts at 1. Each time after, it adds 1 to the count so far.
Watch it run and see per_member grow, a key at a time. Try adding another name to loans on line 1.
Dictionaries inside dictionaries
A value in a dict can be another dict, or a list. Here each member number leads to a dict with the member's name and a list of their loans. Square brackets in a row reach inside, one level each: members["M001"]["name"] is "Sam".
Line 6 reaches in and appends to Ana's list. Inside the f-string on line 8, the keys use single quotes, because the f-string itself uses double quotes.
This is how the library system will store its data until Stage 3, where classes take over.
Check what you learned
Four questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Tutorial: Data Structures, Dictionaries
- Built-in Types: Mapping Types, dict: d[key], del, in, and insertion order
- Built-in Types: dict.get: a default instead of a KeyError
- Built-in Types: dict.items
- The Python Tutorial: Looping Techniques: looping over keys and values with items()
- Built-in Exceptions: KeyError