Chapter 10 — Tuples, Dictionaries & Sets
The module's primary reading · ~45–55 minutes · Objective 6 (choose and use Python's built-in collections (lists, tuples, dictionaries, and sets) with indexing, slicing, mutation, methods, and iteration, and explain aliasing versus copying) · Read it first this week; the lecture, the slides, the tutorial, the quiz, and the Coding Lab all build on it.
In plain language
Last week you kept a pile of values in one list and reached each one by its position; this week you meet three more containers, each built for a different job. A tuple (a fixed record whose parts stay together and never change) holds something like one bike trip. A dictionary (a lookup table that finds a value by its name instead of its position) holds something like your reading log, with each book's title pointing to its pages. A set (a collection that keeps one copy of each value) answers "which ones showed up?" without counting anyone twice. As always, you predict what each program prints and then run it to check.
Why you already care about this
Your phone's contact list does not make you remember that your cousin is contact number 37 in the list. You type a name, and the number comes back. A paper bus ticket works differently: it prints that you got on at stop 3, got off at stop 8, and rode for 20 minutes, and nobody edits a printed ticket afterward. A sign-in sheet at a club fair is different again: when the same person signs 2 times, you still count 1 visitor.
Those are three different jobs: look something up by name, keep a fixed record, and keep each value once. A list from Week 9 can do all three badly. You could hunt through a list of titles for "atlas" and then read the page count at the same position in a second list. It works, but the code is long, and one slip puts the wrong number beside the wrong title. Python gives each job its own container, and picking the right one makes the program short and the mistake hard to make.
This chapter shows you how to build and read a tuple, take one apart in a single line, look up and change values in a dictionary, survive a missing key, walk a dictionary in a predictable order, count things with a one-line idiom, and use a set to drop duplicates. It ends with a way to choose among the four containers you now know.
By the end of this chapter you will be able to:
- build a tuple, read its items by index, and predict the
TypeErrorwhen code tries to change one; - unpack a tuple into names, swap two names in one line, and write a one-item tuple;
- look up, add, and update a value in a dictionary by its key;
- predict a
KeyErrorand repair it with.get()or anintest; - walk a dictionary with
.items()and predict the order it prints in; - tally values with the counting idiom and use a set to drop duplicates;
- pick a list, a tuple, a dictionary, or a set for a given job and say why.
Carry this line with you: a list finds by position; a dictionary finds by name.
Where we are
- Already covered: Week 3 gave you indexing from 0 and
len(); Week 6 gave youforloops and accumulators; Week 7 gave youNoneas the value of "no value"; Week 9 gave you lists, methods that change a list in place, and the difference between an alias and a copy. - This week: tuples and why they cannot change, unpacking and the one-line swap, dictionaries and
KeyError, the counting idiom, insertion order, sets, and choosing the right collection. - How they connect: a tuple reads like a list you cannot change, a dictionary is walked by the same
forloop you used on lists, and a set behaves like a list that refuses repeats. - Where we're going next: Week 11, Strings in Depth & Text Processing, takes text apart into lists and counts words with this week's counting idiom.
Three earlier ideas carry most of the weight. From Week 3, square brackets after a name pick out one item, and an index past the end raises an error. From Week 7, None is the value Python hands back when there is no value to hand back. From Week 9, a list can be changed in place, and in asks whether a value is one of the items. Spend extra time on Sections 3 and 4. Every week after this one leans on dictionaries.
1. Keep a fixed record together: the tuple
A paper bus ticket records three facts about one ride: the stop where you got on, the stop where you got off, and the minutes it took. The three facts belong together, and once the ticket is printed, no one changes them.
A tuple is an ordered collection written with commas, usually inside parentheses, such as (3, 4); you read its items by index, but once it is made it cannot be changed.
Reading a tuple works exactly like reading a list. The first item is at index 0, and len() counts the items.
Worked example — a bike-share trip. This illustrative program stores one bike-share ride as a tuple. Predict both lines before you read them.
trip = ("Dock 4", "Dock 9", 12)
start, finish, minutes = trip
print(f"{start} to {finish}: {minutes} minutes")
print(trip[2])
Output
Dock 4 to Dock 9: 12 minutes
12
Here is the trace.
- The first line builds a tuple of three items: two strings and the number 12.
- The second line hands each item to its own name, in order. Section 2 is about that move.
- The f-string fills in the three names and prints the first line.
trip[2]reads the item at index 2, the third item, which is 12.
In words: the tuple kept the three facts of one ride together, and you read them back by position.
Now try to change one item. This is the pinned tuple program from the course's error set.
spot = (3, 4)
spot[0] = 9
Output
TypeError
Nothing printed, and the last line of the error names TypeError. A tuple is immutable: describes a value that cannot be changed after it is made, such as a tuple or a string; a change means building a new value, and assigning into one of its positions raises TypeError. You met this idea in Week 3 without the word, when a string refused to have one of its characters replaced.
Misconception check. Students often think a tuple is a list with round brackets, so
spot[0] = 9should work. That is tempting, because you read a tuple with the same square brackets as a list. But a tuple has no way to be changed in place, and Python raisesTypeErrorthe moment code tries. The cure: if the values must change, use a list; if they describe one fixed thing, use a tuple and build a new one when the facts change.
In practice (your tools). Paste the spot program into your free browser Python runner and press Run. Read the error from the bottom up: the last line begins with TypeError. Then paste the bike-share program into Python Tutor at pythontutor.com and step through it; the visualizer draws trip as a box labelled tuple with three numbered slots. The Python Tutorial's section 5.3, Tuples and Sequences, on docs.python.org, is the official description.
Memory hook: a tuple is a printed ticket; you read it, you never edit it.
2. Take a tuple apart: unpacking and the one-line swap
When you unpack a grocery bag, you take the items out in order and set each one in its place: bread on the counter, milk in the fridge, apples in the bowl. Python can unpack a tuple the same way, putting each item into its own name in one line.
Unpacking is assigning the items of a tuple or other sequence to several names in one line, in order, as in x, y = spot; the number of names must match the number of items.
A swap is exchanging the values of two names; in Python the one line a, b = b, a does it, because the whole right side is worked out before anything is assigned.
Worked example — the pinned swap program. Predict all three lines.
spot = (3, 4)
x, y = spot
print(x, y)
a = 1
b = 2
a, b = b, a
print(a, b)
print(len((5,)))
Output
3 4
2 1
1
Here is the trace.
x, y = spotsends the first item, 3, toxand the second item, 4, toy. The first line prints 3 4.- On the line
a, b = b, a, Python first works out the right side. It readsbas 2 andaas 1 and packs them as the tuple (2, 1). Only then does it assign:agets 2 andbgets 1. The second line prints 2 1. (5,)is a tuple holding one item, so its length is 1.
In Week 2 you swapped two names with a spare name, temp, in three lines, because giving a its new value first would have lost the old one. The one-line swap needs no spare name, because the right side is finished before any name changes.
A one-item tuple is a tuple that holds a single item, written with a trailing comma, as in (5,); without the comma, (5) is the plain number 5 inside grouping parentheses.
Worked example — the comma makes the tuple. Predict both lines.
print(type((5,)))
print(type((5)))
Output
<class 'tuple'>
<class 'int'>
The first line has a comma, so Python builds a tuple. The second has parentheses and no comma, and parentheses alone only group, the way they grouped (2 + 3) * 4 in Week 1. So (5) is the int 5.
Misconception check. Students often think the parentheses are what make a tuple, so
(5)should be a tuple of one. That is tempting, because every tuple so far was written inside parentheses. But the comma is what makes a tuple; the parentheses only group. The cure: when you want a one-item tuple, write the trailing comma, and runtype()on it if you are unsure.
In practice (your tools). Paste the swap program into Python Tutor and step to the line a, b = b, a. Watch both boxes change on one click of Next, with no spare name ever appearing. Then, in your browser runner, change the line to a, b, c = b, a and run it; the error that comes back shows that the number of names must match the number of items.
Memory hook: right side first, then assign; the comma makes the tuple.
3. Look things up by name: the dictionary
A coat check gives you a ticket with a word on it. You hand back the ticket, and the attendant finds your coat by that word, not by counting hangers from the left. A dictionary works the same way.
A dictionary is a collection of key-value pairs written in curly braces, such as {"atlas": 85}, 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 a dictionary entry that you use to find its value; each key appears once in a dictionary and must be immutable, so a string, number, or tuple works and a list does not.
A key-value pair is one entry of a dictionary: a key written before a colon and the value stored under it written after, as in "atlas": 85.
Worked example — the reading log. Your reading log now keeps one entry per book: each title points to the pages you have read in it. Predict all four lines.
log = {"river book": 120, "atlas": 85}
log["field notes"] = 40
log["atlas"] = log["atlas"] + 15
print(log["atlas"])
print(log.get("comics", 0))
print(len(log))
print(list(log))
Output
100
0
3
['river book', 'atlas', 'field notes']
Here is the trace.
- The first line builds a dictionary with two pairs:
"river book"maps to 120 and"atlas"maps to 85. log["field notes"] = 40uses a key the dictionary does not have yet, so it adds a third pair.log["atlas"] = log["atlas"] + 15reads the old value, 85, adds 15, and stores the sum under the same key: 85 + 15 = 100. The key"atlas"still appears once.print(log["atlas"])prints 100.log.get("comics", 0)asks for a key that is not there and gets back the default, 0. Section 4 is about that line.len(log)counts the pairs. Two pairs to start, plus one added, is 2 + 1 = 3.list(log)builds a list of the keys, in the order they were first added.
In words: square brackets with a key read a value, and square brackets on the left of = add a pair or replace a value.
Misconception check. Students often think assigning to a key that already exists adds a second entry, so the log should now hold four pairs. That is tempting, because
log["field notes"] = 40did add a pair two lines earlier. But a key appears once in a dictionary, so assigning to an existing key replaces its value. The cure: before an assignment, ask whether the key is already there; the run's3confirms that"atlas"was updated, not added again.
Here is a second slip worth seeing once. A dictionary does not number its pairs.
log = {"river book": 120, "atlas": 85}
print(log[0])
Output
KeyError
log[0] does not mean "the first pair." It means "the value stored under the key 0," and there is no such key. Section 4 explains that error.
In practice (your tools). Paste the reading-log program into Python Tutor at pythontutor.com and step through it. The visualizer draws the dictionary as a two-column box, keys on the left and values on the right. Watch a third row appear on the second line and the "atlas" row change from 85 to 100 on the third. The Python Tutorial's section 5.5, Dictionaries, on docs.python.org, is the official description.
Memory hook: a list finds by position; a dictionary finds by name.
4. Read KeyError and use its two cures
You walk up to a library's front desk and ask for a book the library does not own. The librarian does not hand you an empty shelf; the librarian tells you the book is not in the catalog. Python does the same when you ask a dictionary for a key it does not have.
KeyError is the exception Python raises when a program looks up a dictionary key with square brackets and the dictionary has no such key.
Worked example — the pinned missing key. Predict the output.
log = {"atlas": 85}
print(log["comics"])
Output
KeyError
Nothing printed. The lookup failed before print had a value to show, and the last line of the error names KeyError. As always, the type is what you read; the wording after it is not something to memorize.
There are two cures. The first is a method.
.get() is the dictionary method that 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 KeyError.
Worked example — the first cure. Predict both lines.
log = {"river book": 120, "atlas": 85}
print(log.get("comics"))
print(log.get("comics", 0))
Output
None
0
With no default, .get() hands back None, the same "no value" you met in Week 7. With a default of 0, it hands back 0. The pinned one-liner d = {"a": 1} followed by print(d.get("z", 0)) prints 0 for the same reason.
The second cure asks first. The in operator, used on a dictionary, checks whether a value is one of the keys.
Worked example — the second cure. Predict all three lines of the first program, then the one line of the second.
log = {"river book": 120, "atlas": 85}
print(log.get("comics"))
print("atlas" in log)
print(85 in log)
Output
None
True
False
log = {"river book": 120, "atlas": 85}
title = "comics"
if title in log:
print(log[title])
else:
print("not logged yet")
Output
not logged yet
"atlas" in log is True because "atlas" is a key. 85 in log is False, even though 85 is stored in the dictionary, because in checks keys and 85 is a value. In the second program, the if test is False, so the else branch runs and the lookup that would have failed never happens.
Misconception check. Students often think a missing key returns
None, soprint(log["comics"])should printNone. That is tempting, because.get("comics")does printNone, and the two lines look alike. But square brackets raiseKeyErroron a missing key; only.get()hands backNone. The cure: use square brackets when the key must be there, and.get()with a default when it might not be.
Misconception check — what in looks at. Students often think
inon a dictionary checks the values, so85 in logshould beTrue. That is tempting, because 85 is plainly in the dictionary when you print it. Butinon a dictionary checks only the keys. The cure: say "is it a key?" out loud before you predict anintest on a dictionary.
In practice (your tools). In your browser runner, type the pinned missing-key program and press Run. Read the last line of the error and find the type, KeyError. Then change the second line to use .get("comics", 0) and run it again. The Standard Library reference on docs.python.org describes get under the dictionary methods.
Memory hook: brackets demand the key; get asks politely.
5. Walk a dictionary in the order you filled it
A guest list at a party is written in the order people arrive. If you read it top to bottom later, you meet the guests in that same order. A dictionary keeps its keys the same way.
.items() is the dictionary method that 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.
The method .keys() hands back the keys, and .values() hands back the values, each in the same order.
Insertion order is the order in which keys were first added to a dictionary; looping over a dictionary or listing its keys follows this order, which the language has guaranteed since Python 3.7.
Worked example — walking the updated log. This is the log after Section 3's changes. Predict all six lines.
log = {"river book": 120, "atlas": 100, "field notes": 40}
for title, pages in log.items():
print(title, pages)
print(list(log.keys()))
print(list(log.values()))
total = 0
for pages in log.values():
total += pages
print(total)
Output
river book 120
atlas 100
field notes 40
['river book', 'atlas', 'field notes']
[120, 100, 40]
260
Here is the trace.
- Each pass of the first loop gets one pair from
.items()and unpacks it intotitleandpages, the move from Section 2. Three pairs make three lines. list(log.keys())andlist(log.values())list each side, in the same order.- The second loop is the accumulator from Week 6: it starts
totalat 0 and adds each value. The sum is 120 + 100 + 40 = 260.
In words: the loop met the books in the order they went in, and the accumulator added the pages.
Worked example — the pinned insertion-order program. Predict both lines.
d = {}
d["zebra"] = 1
d["apple"] = 2
d["mango"] = 3
print(list(d))
print(list(d.values()))
Output
['zebra', 'apple', 'mango']
[1, 2, 3]
The keys come back in the order they went in, not alphabetically. If the dictionary sorted its keys, "apple" would come first. It does not.
Misconception check. Students often think a dictionary has no order at all, or that it sorts its keys, so they cannot predict a loop's output. That is tempting, because you look things up by name, not by position, and older explanations said the order was not promised. But since Python 3.7 the language guarantees insertion order. The cure: predict a dictionary loop by reading the keys in the order the program added them.
Honesty note: before Python 3.7, keeping insertion order was a detail of one implementation rather than a promise of the language. Every program in this course runs on a newer Python, and the What's New page for Python 3.7 on docs.python.org records the change.
In practice (your tools). Paste the walking program into Python Tutor and watch the loop variables title and pages change together on each pass. Then, in your browser runner, add a fourth line near the top, log["comics"] = 10, and predict where comics will appear in the loop's output before you run it.
Memory hook: a dictionary remembers who came first; it never sorts on its own.
6. Count with a dictionary, and keep keys unchangeable
At a bake sale, someone keeps a tally sheet. Each time a muffin sells, they find the muffin line and add a mark; the first time a new kind sells, they write a new line first. Python does both moves in one line.
The counting idiom is the one-line tally counts[w] = counts.get(w, 0) + 1 inside a loop: get() supplies 0 the first time a key appears, so every item adds one to its own running count.
Worked example — the pinned colour tally. Predict both lines.
words = ["red", "blue", "red", "red", "blue"]
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)
print(counts["red"])
Output
{'red': 3, 'blue': 2}
3
Here is the trace, one pass at a time.
"red": no such key yet, sogethands back 0, and 0 + 1 = 1 is stored."blue": no such key yet, sobluegets 0 + 1 = 1."red"again:gethands back 1, and 1 + 1 = 2 is stored."red"again: 2 + 1 = 3."blue"again: 1 + 1 = 2.
The five words split as 3 + 2 = 5, so every word was counted once. The dictionary prints with its keys in the order each colour first appeared.
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 key that could change after it was stored could never be found again.
Worked example — a tuple key and a list key. Predict the output.
grid = {(3, 4): "corner"}
print(grid[(3, 4)])
shelf = {["atlas"]: 85}
Output
corner
TypeError
The tuple (3, 4) cannot change, so it works as a key, and the lookup prints corner. The third line tries to use a list as a key. A list can change, so Python refuses it and raises TypeError.
Misconception check. Students often think any value can be a key, including a list. That is tempting, because any value can be stored as a dictionary's value. But keys have a stricter rule than values: a key must be immutable. The cure: if you need a key with several parts, use a tuple, not a list.
In practice (your tools). Paste the colour tally into Python Tutor and step through all five passes, watching each count grow in the dictionary's box. Then, in your browser runner, replace the list of colours with the words of a short sentence of your own and predict the tally before you run it.
Memory hook: get supplies the zero; plus one does the counting.
7. Keep one of each: the set
At a club fair, a volunteer stamps the hand of everyone who comes in. When someone leaves and comes back, their hand already has a stamp, so they are not counted again. The volunteer cares who came, not how many times.
A set is an unordered collection that keeps exactly one copy of each value, written in curly braces with no colons or built with set(); it is used to drop duplicates and to test membership with in.
Worked example — the pinned set length. Predict the output.
print(len({1, 2, 2, 3}))
Output
3
The set was typed with four values, but 2 appears twice, so the set keeps 1, 2, and 3. Its length is 3.
Worked example — docks visited. This illustrative program lists the docks where five bike trips ended and asks which docks riders used. Predict all five lines.
docks = ["Dock 4", "Dock 9", "Dock 4", "Dock 2", "Dock 4"]
visited = set(docks)
print(len(docks))
print(len(visited))
print("Dock 9" in visited)
print("Dock 7" in visited)
print(sorted(visited))
Output
5
3
True
False
['Dock 2', 'Dock 4', 'Dock 9']
Here is the trace.
- The list holds five trips, so
len(docks)is 5. set(docks)keeps one copy of each dock."Dock 4"appears three times, so two repeats are dropped, and 5 − 2 = 3."Dock 9"is in the set, so the test isTrue;"Dock 7"is not, so it isFalse.sorted(visited)builds a new list in sorted order, so it always prints the same way.
Why wrap the set in sorted()? A set has no order you can count on. The order in which a set prints is not part of the language, so this course never asks you to predict it. You predict a set's length and its membership tests, and when you want to show its items, you print sorted() of it.
Worked example — empty braces. Predict both lines.
print(type({}))
print(type(set()))
Output
<class 'dict'>
<class 'set'>
Empty curly braces make an empty dictionary, because dictionaries had the braces first. The empty set is written set().
Misconception check. Students often think a set keeps the order you typed, so they predict its printed order with confidence. That is tempting, because a list and a dictionary both keep an order you can predict. But a set promises no order at all. The cure: never predict a set's printed order; predict its
len, test membership within, and usesorted()when you need to show the items.
Misconception check — empty braces. Students often think
{}is an empty set, because a set is written with curly braces. That is tempting, but{}builds an empty dictionary. The cure: writeset()for an empty set, and check withtype()when you are unsure.
In practice (your tools). In your browser runner, type the docks program and press Run. Then add "Dock 9" to the end of the list and predict which of the five lines change before you run it again. The Python Tutorial's section 5.4, Sets, on docs.python.org, describes sets and notes that the empty set is written set().
Memory hook: a set counts who came, not how often.
8. Choose the right collection, and check a chatbot with a run
A carpenter carries a hammer, a saw, a level, and a tape measure. Each tool can be misused for another's job, but the right one makes the work fast and the mistakes rare. You now carry four containers, and the question each time is which job you are doing.
Here are the four jobs, each matched with the container that fits it and an example from this chapter or Week 9.
| The job | The container | Example |
|---|---|---|
| Look a value up by name | dictionary | The reading log, title to pages |
| Keep each value once, test membership | set | The docks riders used |
| Hold a fixed record that will not change | tuple | One bike-share trip |
| Keep an ordered sequence you will change | list | Seven days of pages in Week 9 |
Worked example — a chatbot's claim about a missing key. Suppose you ask a chatbot what the pinned missing-key program prints, and it answers: "the key is missing, so the program prints None." Run the pinned program and compare.
log = {"atlas": 85}
print(log["comics"])
Output
KeyError
The run raised KeyError and printed nothing. The chatbot mixed up square brackets with .get(), which is the exact slip from Section 4. If you want the chatbot's claim to be true, the program must use .get():
log = {"atlas": 85}
print(log.get("comics"))
Output
None
In words: the run caught a claim that sounded reasonable, and the cure was the one-method change from Section 4. The computer does exactly what you wrote, not what you meant.
Misconception check. Students often think one container is always best, so they use a list for everything because it came first. That is tempting, because a list can hold anything. But a list makes you search by position for a value you know by name, and it keeps every repeat. The cure: before you write the first line, name the job from the table above, and let the job pick the container.
In practice (your tools). Ask your approved chatbot to write a program that counts how many times each letter appears in the word "banana" and to tell you what it prints. Before you run its code, write down your own prediction. Then run it in your browser runner and compare every line with the chatbot's claim. If its program prints a set, check that it predicted the set's length and not its order. 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.
Caveat: this chapter covers only the collection tools Week 10 needs. Dictionary and set comprehensions, set algebra, the del statement, collections.Counter, and dictionaries inside dictionaries all come later.
Pause and choose one of these to think about before you read on:
- (a) Think of something in your own life you look up by name, such as a phone's contact list, a class schedule, or a pantry list. Would you store it as a dictionary, and what would the keys and the values be?
- (b) Think of a list you keep that has repeats, such as the songs you played this week or the places you shopped. What question would a set of it answer that the list does not, and what would you lose by turning it into a set?
Memory hook: name the job first; the job picks the container.
Key terms
- tuple — An ordered collection written with commas, usually inside parentheses, such as (3, 4); you read its items by index, but once it is made it cannot be changed. (first used: 1. Keep a fixed record together: the tuple)
- immutable — Describes a value that cannot be changed after it is made, such as a tuple or a string; a change means building a new value, and assigning into one of its positions raises TypeError. (first used: 1. Keep a fixed record together: the tuple)
- unpacking — Assigning the items of a tuple or other sequence to several names in one line, in order, as in x, y = spot; the number of names must match the number of items. (first used: 2. Take a tuple apart: unpacking and the one-line swap)
- swap — Exchanging the values of two names; in Python the one line a, b = b, a does it, because the whole right side is worked out before anything is assigned. (first used: 2. Take a tuple apart: unpacking and the one-line swap)
- one-item tuple — A tuple that holds a single item, written with a trailing comma, as in (5,); without the comma, (5) is the plain number 5 inside grouping parentheses. (first used: 2. Take a tuple apart: unpacking and the one-line swap)
- dictionary — A collection of key-value pairs written in curly braces, such as {"atlas": 85}, in which you look up, add, or update a value by giving its key rather than a position. (first used: 3. Look things up by name: the dictionary)
- key — The name-like part of a dictionary entry that you use to find its value; each key appears once in a dictionary and must be immutable, so a string, number, or tuple works and a list does not. (first used: 3. Look things up by name: the dictionary)
- key-value pair — One entry of a dictionary: a key written before a colon and the value stored under it written after, as in "atlas": 85. (first used: 3. Look things up by name: the dictionary)
- KeyError — The exception Python raises when a program looks up a dictionary key with square brackets and the dictionary has no such key. (first used: 4. Read KeyError and use its two cures)
- .get() — The dictionary method that 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 KeyError. (first used: 4. Read KeyError and use its two cures)
- .items() — The dictionary method that 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. (first used: 5. Walk a dictionary in the order you filled it)
- insertion order — The order in which keys were first added to a dictionary; looping over a dictionary or listing its keys follows this order, which the language has guaranteed since Python 3.7. (first used: 5. Walk a dictionary in the order you filled it)
- counting idiom — The one-line tally counts[w] = counts.get(w, 0) + 1 inside a loop: get() supplies 0 the first time a key appears, so every item adds one to its own running count. (first used: 6. Count with a dictionary, and keep keys unchangeable)
- set — An unordered collection that keeps exactly one copy of each value, written in curly braces with no colons or built with set(); it is used to drop duplicates and to test membership with in. (first used: 7. Keep one of each: the set)
Summary
- A tuple is a fixed record; assigning into one raises
TypeError. x, y = spotunpacks a tuple;a, b = b, aswaps two names.- The comma makes a tuple:
(5,)is a tuple,(5)is an int. - A dictionary finds a value by its key, not its position.
- Assigning to a new key adds a pair; to an existing key, it replaces the value.
- A missing key raises
KeyError;.get()with a default avoids it. inon a dictionary checks the keys, never the values.- A dictionary loops in insertion order, guaranteed since Python 3.7.
- The counting idiom is
counts[w] = counts.get(w, 0) + 1. - A set keeps one of each value; key its
len, never its printed order. {}is an empty dictionary;set()is an empty set.
Check your understanding
Work these before looking at the answers — they are ungraded, and the answers (with reasoning) are at the bottom of the page.
- A café order in an illustrative example is stored as
order = ("tea", 3). The program runsdrink, cups = order, thenprint(drink, cups), thenorder[1] = 4. Predict what the program prints. - A campus club fair in an illustrative example keeps
clubs = {"chess": 12, "film": 20}, the sign-ups for each club. The program runsclubs["chess"] = clubs["chess"] + 3, then printsclubs["chess"], thenclubs.get("drama", 0), thenlen(clubs). Predict the three lines. - A coin game in an illustrative example records
flips = ["heads", "tails", "heads", "heads"]and tallies them with the counting idiom into an empty dictionary namedtally. Predict whatprint(tally)shows. - A library door in an illustrative example logs badge numbers
scans = [101, 205, 101, 330, 205, 101]and buildsvisitors = set(scans). Predictlen(scans),len(visitors), and330 in visitors, and say why you would not predict whatprint(visitors)shows.
Answers (worked reasoning — read after attempting)
- The program prints tea 3, and then the run stops with
TypeError. Unpacking sends"tea"todrinkand 3 tocups, so the first line is tea 3. Thenorder[1] = 4tries to change a tuple, and a tuple is immutable. If the number of cups must change, the order belongs in a list or a new tuple. - The lines are 15, then 0, then 2. The update reads 12 and stores 12 + 3 = 15 under the same key.
"drama"is not a key, so.get()hands back the default 0 instead of raisingKeyError. The update replaced a value and added no pair, so the dictionary still holds 2 pairs. - It shows
{'heads': 3, 'tails': 1}. The first"heads"gets 0 + 1 = 1,"tails"gets 0 + 1 = 1, and the next two"heads"raise its count to 2 and then 3. The keys print in the order each first appeared, and 3 + 1 = 4 matches the four flips. len(scans)is 6,len(visitors)is 3, and330 in visitorsisTrue. The list has six scans, but 101 appears three times and 205 twice, so the set keeps three badge numbers: 6 − 2 − 1 = 3. You would not predict the printed order ofvisitors, because a set promises no order; printsorted(visitors)when you need a predictable display.
Next up in this module: the Readings & Resources page, the lecture tutorial, the practice set, and the quiz — and next week, the string method split turns a line of text into a list whose words you can tally with this week's counting idiom.
Built with The Course Maker · samples.thecoursemaker.com