Lecture: Tuples, Dictionaries & Sets
Lecture script · about 15–20 minutes spoken · Week 10
Opening
Think about a biology major who keeps a count for every sample label in a lab notebook. Nobody wants to remember that a sample is entry number 37. You want to say the label and get the count back.
A business student tallies which products sold on a receipt log. A city-planning intern asks which bike-share docks riders actually used. Three jobs: look a value up by name, count things, keep each value once.
In Week 9 you met the list, which keeps many values in order and finds each one by its position. In Week 7 you met None, the value Python hands back when there is no value to hand back. In this lecture you meet three more containers, the tuple, the dictionary, and the set, and you learn which job each one does best. In Week 11 you'll take text apart into lists and count its words, and this week's counting trick is the one you'll use.
Here's the plan. We'll work through tuples, then dictionaries, then sets. Then we'll choose the right container and check a chatbot with a run.
1. Keep a fixed record together
Picture a paper bus ticket. It records where you got on, where you got off, and how long the ride took, and nobody edits it once it's printed.
Python's version of that ticket is a tuple. A tuple is an ordered collection written with commas, usually inside parentheses; you read its items by index, but once it is made it cannot be changed. You read a tuple exactly the way you read a list: the first item is at index 0.
Here's an example from bike-share. A tuple named trip holds three items: the string Dock 4, the string Dock 9, and the number 12, the minutes the ride took. The program unpacks the trip into three names and prints a sentence that reads Dock 4 to Dock 9, 12 minutes. Then it prints trip at index 2, and the program displays 12, the third item.
Now try to change one. The course's pinned program makes a tuple named spot holding 3 and 4, and then tries to assign 9 into spot at index 0. Nothing prints. Python raises a TypeError, and you find that type on the last line of the error. A tuple is immutable, which describes a value that cannot be changed after it is made.
The classic mix-up is thinking a tuple is a list with round brackets. It reads like a list, but it has no way to be changed in place.
Pause and try this. The trip tuple holds Dock 4, Dock 9, and 12. What does trip at index 2 display, and what happens if code assigns a new number into that position?
Count from 0, and remember what kind of container it is.
Here's the answer. Trip at index 2 displays 12, the third item. Assigning into that position raises a TypeError, because a tuple is immutable.
A tuple is a printed ticket. You read it; you never edit it.
2. Take a tuple apart in one line
Think about unpacking a grocery bag: bread on the counter, milk in the fridge, apples in the bowl, each in its place.
Python does that in one line, and the move is called unpacking: assigning the items of a tuple or other sequence to several names in one line, in order. The number of names must match the number of items.
Here's the pinned program. It starts with spot, holding 3 and 4. The line x comma y equals spot sends 3 to x and 4 to y, so printing x and y displays 3 4. Next, a gets 1 and b gets 2. Then comes the line a comma b equals b comma a. That's a swap, exchanging the values of two names. Python works out the whole right side first. It reads b as 2 and a as 1, packs them together, and only then assigns. So a gets 2, b gets 1, and the program displays 2 1.
In Week 2 you swapped two names with a spare name called temp, in three lines. The one-line swap needs no spare, because the right side is finished before any name changes.
The last line of the pinned program prints the length of a one-item tuple, a tuple that holds a single item, written with a trailing comma. It displays 1. Without the comma, 5 in parentheses is the plain number 5, an int. Parentheses alone only group, the way they grouped 2 plus 3 in Week 1.
Pause and try this. After a gets 1, b gets 2, and the one-line swap runs, what do a and b hold?
Remember which side Python finishes first.
Here's the answer. A holds 2 and b holds 1. Python worked out the right side, 2 and 1, before it assigned anything.
Right side first, then assign; and the comma makes the tuple.
3. Look things up by name
Picture a coat check. The attendant finds your coat by the word on your ticket, not by counting hangers from the left.
That's a dictionary: a collection of key-value pairs written in curly braces, in which you look up, add, or update a value by giving its key rather than a position. A key is the name-like part of an entry that you use to find its value. Each key appears once, and it must be immutable, so a string, a number, or a tuple works and a list does not. One entry, a key and the value stored under it, is a key-value pair.
Here's the reading log's stage for this week. The log is a dictionary with two pairs. The key river book maps to 120 pages, and the key atlas maps to 85. The next line assigns 40 under the key field notes, which isn't there yet, so a third pair is added. Then the program reads atlas, adds 15, and stores the sum back under atlas. 85 plus 15 is 100. Printing atlas displays 100. The length of the log, the number of pairs, is 3. And listing the log gives its keys in the order they went in: river book, atlas, field notes.
The classic mix-up is thinking that assigning to an existing key adds a second entry. It doesn't; the assignment replaces the value.
Pause and try this. The log starts with two pairs. One line adds field notes, and another line updates atlas. How many pairs does the log hold at the end?
Ask whether each key was new or already there.
Here's the answer. It holds 3 pairs. Field notes was a new key, so it added a pair, and atlas already existed, so its value was replaced with 100.
A list finds by position; a dictionary finds by name.
4. Read KeyError and use its two cures
Ask a library desk for a book the library doesn't own, and you're told it isn't in the catalog.
Python does the same with a KeyError, the exception Python raises when a program looks up a dictionary key with square brackets and the dictionary has no such key. The pinned program makes a log holding only atlas with 85, and then prints the value under comics. Nothing prints. The last line of the error names KeyError.
There are two cures. The first is the method .get(), read aloud as dot get. It hands back the value stored under a key, or the default given as its second argument when the key is missing, or None when no default is given. It never raises a KeyError. So asking the log to get comics with a default of 0 displays 0. Asking it to get comics with no default displays None.
The second cure asks first. The word in, used on a dictionary, checks whether a value is one of the keys. Is atlas in the log? True. Is 85 in the log? False, even though 85 is stored there, because in checks keys and 85 is a value. A program that tests whether comics is in the log before it looks it up takes the else branch and displays the words not logged yet.
The classic mix-up is believing a missing key returns None. Only dot get does that. Square brackets raise a KeyError.
Pause and try this. The log holds atlas with 85. What does asking for comics with square brackets do, and what does asking with dot get and a default of 0 do?
Brackets and get handle a missing key differently.
Here's the answer. Square brackets raise a KeyError and print nothing. Dot get with a default of 0 hands back 0, because the key is missing.
Brackets demand the key; get asks politely.
5. Walk a dictionary in the order you filled it
Think of a party guest list, written in the order people arrive. Read it later, and you meet the guests in that order.
A dictionary keeps its keys that way. The method .items(), read aloud as dot items, hands back every key together with its value as a pair, in insertion order, so a for loop can unpack each pair into two names. Insertion order is the order in which keys were first added to a dictionary, and the language has guaranteed it since Python 3.7.
Here's the updated log, with river book at 120, atlas at 100, and field notes at 40. A for loop over the items unpacks each pair into a title and a page count and prints them. The program displays river book 120, then atlas 100, then field notes 40. Listing the values gives 120, 100, and 40. Then an accumulator from Week 6 starts a total at 0 and adds each value. 120 plus 100 plus 40 is 260, so it displays 260.
The pinned insertion-order program makes the point sharper. It adds three keys: zebra, then apple, then mango. Listing the keys gives zebra, apple, mango, in the order they went in. If a dictionary sorted its keys, apple would come first. It doesn't.
An honest caveat: before Python 3.7, insertion order was a detail of one implementation, not a promise.
Pause and try this. A dictionary gets zebra, then apple, then mango. In what order does a loop over its keys meet them?
Think about the guest list.
Here's the answer. Zebra, apple, mango. A dictionary keeps insertion order, so the loop meets the keys in the order they were added.
A dictionary remembers who came first; it never sorts on its own.
6. Count with a dictionary, and keep keys unchangeable
Picture a bake-sale tally sheet. A sale adds a mark to its line, and a new kind of muffin gets a new line first.
The counting idiom does both moves in one line inside a loop: counts at w gets counts dot get of w with a default of 0, plus 1. Get supplies 0 the first time a key appears, so every item adds one to its own running count.
Here's the pinned tally. The list holds five colour words: red, blue, red, red, blue. Red climbs to 3 and blue to 2, one count at a time. The program displays a dictionary with red at 3 and blue at 2, and then the count for red alone, 3. 3 plus 2 is 5, one count for each word.
Now the rule that keeps a dictionary working. A key must be immutable, because the dictionary finds a value by the key's exact contents. A dictionary named grid with the tuple 3, 4 as its key and the word corner as its value works fine, and looking up that tuple displays corner. But a dictionary that tries to use a list as its key raises a TypeError, because a list can change.
Pause and try this. In the colour tally, what is red's count right after the second red is counted?
Walk the list one word at a time.
Here's the answer. It's 2. The first red stored 0 plus 1, which is 1, and the second red read that 1 and stored 1 plus 1, which is 2.
Get supplies the zero; plus one does the counting.
7. Keep one of each with a set
Think of a volunteer stamping hands at a club fair. Someone who comes back already has a stamp, so they aren't counted again.
That's a set: an unordered collection that keeps exactly one copy of each value. It's used to drop duplicates and to test membership with in. The pinned program asks for the length of a set typed with 1, 2, 2, and 3. The repeated 2 is kept once, so the set holds three values and the program displays 3.
Here's a bike-share example. A list records the docks where five trips ended: Dock 4, Dock 9, Dock 4, Dock 2, Dock 4. Turn the list into a set named visited. The list's length is 5. The set's length is 3, because two repeats of Dock 4 are dropped, and 5 minus 2 is 3. Is Dock 9 in visited? True. Is Dock 7? False.
Now the part that trips people up. A set promises no order, so this course never asks you to predict the order it prints in. You predict its length and its membership tests. To display its items, you print the sorted version, which gives Dock 2, Dock 4, Dock 9 every time.
One more trap. Empty curly braces make an empty dictionary, not an empty set. The empty set is written set with empty parentheses.
Pause and try this. Five trips ended at Dock 4, Dock 9, Dock 4, Dock 2, and Dock 4. How many docks are in the set, and would you predict the set's printed order?
Count the different docks, not the trips.
Here's the answer. The set holds 3 docks. You would not predict its printed order, because a set promises no order; you'd print the sorted version instead.
A set counts who came, not how often.
8. Choose the right container, and check a chatbot with a run
A carpenter carries a hammer, a saw, and a tape measure, and picks the one that fits the job.
You now carry four containers, and each has a job. To look a value up by name, use a dictionary, like the reading log. To keep each value once and test membership, use a set, like the docks riders used. To hold a fixed record, use a tuple, like one bike trip. To keep an ordered sequence you'll change, use a list, like the days of pages from Week 9.
Suppose you ask a chatbot what the pinned missing-key program prints, and it answers that the key is missing, so the program prints None. You run it. The program raises a KeyError and prints nothing. The chatbot mixed up square brackets with dot get. If you want its claim to be true, the program must use dot get, and then the run displays None. The computer does exactly what you wrote, not what you meant.
For the official word, the Python Tutorial's sections 5.3, 5.4, and 5.5 on docs.python.org are where tuples, sets, and dictionaries are written down. One honest limit of this lecture: dictionary and set comprehensions, set algebra, the del statement, and dictionaries inside dictionaries all come later.
Pause and try this. You need to keep the names of everyone who signed in at a club fair, with no one listed twice, and you want to ask whether a given name signed in. Which container fits?
Name the job first.
Here's the answer. A set. It keeps one copy of each value, and in tests membership.
Name the job first; the job picks the container.
Closing
Let me pull it together. A tuple is a fixed record, so assigning into spot raised a TypeError. Unpacking hands a tuple's items to several names, and the one-line swap turned 1 and 2 into 2 and 1. A dictionary finds a value by its key, so updating atlas gave 100 and the log held 3 pairs. A missing key raises a KeyError, and dot get with a default, or an in test on the keys, avoids it. A dictionary walks in insertion order, guaranteed since Python 3.7, and the pages totalled 260. The counting idiom turned five colour words into red 3 and blue 2, and a key must be immutable. A set keeps one of each, so five trips came down to 3 docks, and you predict its length, never its order. And the job picks the container, while the run checks the chatbot.
Next in this module come the slide deck, the Readings and Resources page, the lecture tutorial, the practice set, the quiz, the discussion, and the Coding Lab. Then, in Week 11, Strings in Depth and Text Processing, you'll split a line of text into a list of words and count them with this week's counting idiom.
Built with The Course Maker · samples.thecoursemaker.com