A dictionary with a default
A dictionary hands you a value when you ask for it by its key, tells you when the key is not there, and counts in one line once you give it a default.
- Reach for it when
- You look something up by what it is, not by where it is.
- The move
counts[key, default: 0] += 1counts. A plain lookup hands back an optional, because the key may not be there.- Cost
- A lookup or an update is one step, on average.
The idea
I asked at the library how many books I have out. The man at the desk wouldn't say none.
How many do you have out?
None! I've never even joined. We'll come back to him. Behind his desk is a drawer of cards, one for each reader: a name, and how many books that reader has out. Find me Ada's.
I ask for it by name and it's in my hand. Ada, 2. I don't count along to the fortieth card. That's a dictionary: you look a thing up by what it is, not by where it is.
Now find me Harper's.
There's no card for Harper.
So Harper has zero books out.
I didn't say zero. Grace has a card that says 0. You have no card. Swift keeps those two answers apart: ask for a card and you get the card or nil, and you look at which before you read a number off it.
Fussy. Suppose I'm counting. Each time a number turns up I want one more on its card, and the first time, it has no card.
Then say so as you ask. counts[number, default: 0] += 1: where there's no card, read it as 0. Then add 1, and now there is a card.
One line. And that's all of counting?
All of it. You'll write that line more often than your own name.
Good. Now read me the drawer from front to back.
It has no front. It's a drawer, not a shelf. Tip it out today and again tomorrow, and the cards may land in a different order. If you want an order, sort the names yourself.
And the man at the desk? Was he being difficult?
He was being a dictionary. You asked him a plain question about a card that isn't there.
That is the whole tool: a drawer that hands you a card when you ask for it by name, tells you when there is none, and reads a missing card as 0 when you ask it to. Everything else in this lesson is that drawer with one thing added at a time.
The shape
This is what you know by heart:
/// How many times each number appears in `numbers`.
func countNumbers(_ numbers: [Int]) -> [Int: Int] {
var counts: [Int: Int] = [:] // an empty drawer: no cards yet
for number in numbers {
counts[number, default: 0] += 1 // no card? read it as 0. Then one more.
}
return counts // one card for each different number
}It has four parts, and each is there for a reason.
- The empty drawer. What you ask by is the key, and what the card says is the value.
[Int: Int]names their types, the key's first. Here a key is a number from the array, and its value is how many times that number has come.[:]is a dictionary with nothing in it. It cannot say what the cards will hold, so the types are written out. - The default.
counts[number, default: 0]asks for the card fornumber, and says what to read when there is no card: 0. - The update.
+= 1takes what was read, adds one, and stores the result under the key. A number that had no card now has one, and it says 1. - The answer. After the loop the drawer holds one card for each different number, and each card says how many times its number came.
Nothing is searched. The key leads straight to its card, in one step on average, however many cards the drawer holds.
Watch it run
The numbers are 7, 9, 7, 7 and 9. Here is the drawer as each one arrives.
| number | its card before | read with the default | the drawer after |
|---|---|---|---|
| 7 | no card | 0 | [7: 1] |
| 9 | no card | 0 | [7: 1, 9: 1] |
| 7 | 1 | 1 | [7: 2, 9: 1] |
| 7 | 2 | 2 | [7: 3, 9: 1] |
| 9 | 1 | 1 | [7: 3, 9: 2] |
The answer is [7: 3, 9: 2]. Look at the second row. The drawer holds a card, but not one for 9, so the default gives 0 and += 1 puts in a card that says 1. In the third row 7 has its card, and the default is not used. That is all the default does: it stands in for a card that is not there yet.
Step by step
Store a value under a key and read it back
Start with the library's drawer. Two arrays say who has what: names[i] has books[i] books out.
/// One card for each reader: `names[i]` has `books[i]` books out.
/// When a name comes more than once, its last number is the one that stays.
func cards(_ names: [String], _ books: [Int]) -> [String: Int] {
var booksOut: [String: Int] = [:] // the keys are names, the values are numbers
for i in names.indices {
booksOut[names[i]] = books[i] // store the number under the name
}
return booksOut
}What is new: booksOut[names[i]] = books[i] stores a value under a key. The square brackets hold a key where an array's hold a position, and here the key is a name.
A key holds one value. Store under a name that has no card, and a card is added. Store under a name that has one, and its number is replaced. So for Ada with 2, Grace with 0 and then Ada again with 3, the drawer is ["Ada": 3, "Grace": 0]: its count is 2, and Ada's card says 3.
The same brackets read a value back: booksOut["Ada"] gives Optional(3). The 3 is there, but wrapped. The next step says why.
Look up a key that isn't there, and unwrap what comes back with if let
Ask the same drawer for Harper, who has never joined. booksOut["Harper"] gives nil.
That is why the 3 came back wrapped. A lookup cannot promise a value, because the key may not be there, so it hands back a value or nothing. Swift calls that an optional, and you open it before you use the number inside:
/// What the library says about a name: how many books are out, or that there is no card.
func report(_ name: String, _ booksOut: [String: Int]) -> String {
if let books = booksOut[name] { // a card came back: `books` is its number
return "\(name) has \(books) out"
} else { // nil came back: no card for this name
return "\(name) has no card"
}
}What is new: a lookup's answer has to be opened, and if let books = booksOut[name] opens it. When a card comes back, books is the plain number on it and the first branch runs. When nil comes back, the else runs.
For Ada it gives "Ada has 3 out". For Harper it gives "Harper has no card". For Grace it gives "Grace has 0 out": her card says 0, and it is still a card. No card and a card that says 0 are different answers, and if let tells them apart.
Count how many times each number appears
With the first two steps you can already count. Look the number up. If there is a card, store one more. If there is none, store 1.
func countNumbersTheLongWay(_ numbers: [Int]) -> [Int: Int] {
var counts: [Int: Int] = [:]
for number in numbers {
if let count = counts[number] { // there is a card: store one more
counts[number] = count + 1
} else { // no card: make one that says 1
counts[number] = 1
}
}
return counts
}For 7, 9, 7, 7, 9 it gives [7: 3, 9: 2], which is right. But every pass asks the same question: is there a card yet?
What is new: the default. counts[number, default: 0] is a lookup that cannot come back empty. Where there is no card it reads as 0, a plain number with nothing to unwrap. So the question folds into the lookup, and the five lines of the if become one: counts[number, default: 0] += 1. This step is the shape, written from an empty function.
Reading with a default does not put a card in the drawer. After counting 7, 9, 7, 7, 9, counts[4, default: 0] gives 0, and the drawer still holds 2 cards. Only storing makes a card, and += 1 stores.
Count each character of a string
/// How many times each character appears in `text`.
func countCharacters(_ text: String) -> [Character: Int] {
var counts: [Character: Int] = [:] // the only change: a key is a character
for character in text {
counts[character, default: 0] += 1
}
return counts
}What is new: the key is a Character. The loop goes through the string one character at a time, and the line that counts does not change. For banana it gives ["a": 3, "b": 1, "n": 2].
A key can be a number, a string or a character, and any character will do. For Anna the answer is ["A": 1, "a": 1, "n": 2]: A and a are different characters, so each has a card of its own. A space would have one too.
An array of 26 slots, as in the lesson "Characters as numbers", has room for the lowercase letters and nothing else. A dictionary takes whatever turns up, and makes a card only for what did.
Loop over the keys and values
Walk a dictionary, and each pass hands you one card as a pair: its key, then its value.
/// The sum of the numbers that were counted: each number, once for every time it came.
func sumFromCounts(_ counts: [Int: Int]) -> Int {
var total = 0
for (number, count) in counts { // one card each pass: its key and its value
total += number * count
}
return total
}What is new: for (number, count) in counts. For the counts of 7, 9, 7, 7, 9 the loop adds 7 three times and 9 twice, and gives 39. Added up one at a time, the five numbers give 39 too. The counts hold everything the array held, except its order.
The loop hands you every card once. It does not hand them over in an order you can count on. Walk the same dictionary twice without changing it, and the order is the same both times: that is all Swift promises. Change it, or run the program again, and the cards can come out differently. A sum does not mind. A list does.
This step has a second half, with a new thing of its own: when the order will show in the answer, sort the keys and walk those.
/// One line for each key, as `key: value`, smallest key first.
func sortedLines(_ counts: [Int: Int]) -> [String] {
var lines: [String] = []
for number in counts.keys.sorted() { // the keys in order: the same on every run
lines.append("\(number): \(counts[number, default: 0])")
}
return lines
}counts.keys is every key, and sorted() puts them in order, smallest first. This gives ["7: 3", "9: 2"], on every run. Every dictionary in this lesson was printed with its keys sorted, for that reason. The lesson "Sorting by a key" has the rest of sorting.
The value is read with counts[number, default: 0]. The key has come straight out of the drawer, so its card is there and the default is never used. It is written because a plain lookup would hand back an optional, and this hands back a plain number.
The key with the largest value
Whose card has the largest number? Walk the names in order, and hold on to one of them: the best so far.
/// The name with the largest number. When several names share the largest number,
/// the one that comes first in the alphabet. `booksOut` is never empty.
func nameWithMost(_ booksOut: [String: Int]) -> String {
let names = booksOut.keys.sorted() // a fixed order: A to Z
var best = names[0] // start from a real name
for name in names {
if booksOut[name, default: 0] > booksOut[best, default: 0] {
best = name // strictly more, so a tie changes nothing
}
}
return best
}What is new: keeping the best key so far. best starts as a real name, the first one. Each name's number is then compared with the number of the name being held, both read through the drawer, and a name with strictly more takes its place. The lesson "Best so far" is about this loop and nothing else.
For Ada with 3, Grace with 5 and Lin with 5 it gives Grace.
Grace and Lin tie. So the problem has to say who wins, and this one says the first in the alphabet. Two things in the code make it so. The names are sorted, so Grace is met before Lin. And > is strict, so Lin, with exactly as many, does not take her place. With >= the answer would be Lin.
In an array "the first of them" means something. In a drawer it means nothing until you sort.
Take a key out when its count reaches zero
Books come back. Each one takes 1 off a card, and a card that reaches 0 comes out of the drawer.
/// How many readers still have a book out. `borrowed` has a name for each book taken out,
/// and `returned` has a name for each book brought back.
func readersWithBooks(_ borrowed: [String], _ returned: [String]) -> Int {
var booksOut: [String: Int] = [:]
for name in borrowed {
booksOut[name, default: 0] += 1 // one more on the card
}
for name in returned {
booksOut[name, default: 0] -= 1 // one fewer on the card
if booksOut[name] == 0 { // the card says zero
booksOut[name] = nil // take the card out of the drawer
}
}
return booksOut.count // one card for each reader with a book out
}What is new: booksOut[name] = nil takes the key out. Storing nil does not leave an empty card. It removes the card.
The line above it compares a plain lookup with 0. That is allowed: an optional equals 0 only when there is a card and the card says 0.
Ada takes out three books and Grace two. Then Grace brings both of hers back. The function gives 1: only Ada still has a book out.
The card has to come out because booksOut.count counts cards, not books. Leave Grace's card in, and the drawer is ["Ada": 3, "Grace": 0]: 2 cards, for one reader with books. A key with a count of zero still counts as a key.
What goes wrong
Forcing the lookup. ! opens an optional without looking.
func countNumbersForced(_ numbers: [Int]) -> [Int: Int] {
var counts: [Int: Int] = [:]
for number in numbers {
counts[number]! += 1 // wrong: `!` promises a card is there
}
return counts
}It compiles. Then, for 7, 9, 7, it stops on the first 7. The drawer is empty, so counts[7] is nil, and ! on nil stops the program with "Unexpectedly found nil while unwrapping an Optional value". ! is a promise that the card is there. The first time a key turns up, it never is.
Leaning on the order. The lesson's code counted 7, 9, 7, 7, 9 into 200 separate drawers, and asked each for Array(counts.keys). The same two cards came out as [7, 9] and [9, 7]. A check that expects one of those passes on some runs and fails on others. counts.keys.sorted() gave [7, 9] every time.
A tie with nobody to settle it. Take the sort out of step 6, and 200 drawers that all hold Ada 3, Grace 5 and Lin 5 give two answers, Grace and Lin: each names whichever it happens to hand over first. Say which key wins, sort the keys, and compare with >.
An alphabet with capitals in it. In the order sorted() uses, every capital from A to Z comes before every lowercase letter from a to z: ada, Zoe and Bea come out as ["Bea", "Zoe", "ada"]. Sorted names are in the order of the alphabet only when they are written alike.
A card that says zero. Leave out step 7's nil line, and Grace keeps her card: the drawer is ["Ada": 3, "Grace": 0]. count says 2 where the answer is 1, and a loop over the drawer visits a reader with no books. A key whose count has reached zero is still a key until you set it to nil.
Counting down a key that is not there. counts[4, default: 0] -= 1, on the counts of 7, 9, 7, 7, 9, reads a blank card, takes 1 off it and stores it: [4: -1, 7: 3, 9: 2]. The default makes that as easy as counting up. Count down only a key that you know has a card.
A default where the question was "is there a card?" booksOut["Harper", default: 0] gives 0, as if Harper had a card with nothing on it. When no card and zero mean different things, use the plain lookup and if let.
Say it back
What does a plain lookup, booksOut[name], hand back?
Show the answerHide the answer
An optional: the value, or nil when there is no card for that key. if let opens it.
What does counts[number, default: 0] += 1 do the first time a number turns up?
Show the answerHide the answer
There is no card, so the lookup reads as 0. One is added and stored under the key, and now there is a card.
Does reading with a default put a card in the drawer?
Show the answerHide the answer
No. counts[4, default: 0] gives 0 and stores nothing. Only storing makes a card: =, += and -=.
The answer is a list made from a dictionary. What do you do before you walk it, and why?
Show the answerHide the answer
Sort the keys: counts.keys.sorted(). A dictionary keeps its cards in no order, and two runs can hand them over differently.
Two keys tie for the largest value. Which one does the loop return?
Show the answerHide the answer
The one the problem names. Here that is the first in sorted order: the keys are sorted, and > lets a later key in only when it has strictly more.
A count reaches zero. What do you do, and what happens if you don't?
Show the answerHide the answer
Set the key to nil, which takes the card out. If you don't, the card stays, and count counts a key that stands for nothing.
Why wouldn't the man at the desk say that Harper had no books out?
Show the answerHide the answer
There was no card for her. A plain lookup of a name that is not there hands back nil, and nil is not 0: only a card can say none. Had she asked the way a count does, with booksOut["Harper", default: 0], he would have said 0.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | A card for each name | Easy |
| 2 | Is there a card? | Easy |
| 3 | Count each number | Easy |
| 4 | The count that stops the program | Easy |
| 5 | Count each character | Easy |
| 6 | The sum, from the counts | Easy |
| 7 | Every key and its value, in order | Easy |
| 8 | The name with the largest number | Easy |
| 9 | The answer changes from run to run | Easy |
| 10 | How many readers still have a book out? | Easy |
These problems are done in the Orithms Mac app.
Every piece of code and every number in a lesson comes from a file that was compiled and run.