10 Dicts
A dict, short for dictionary, files values under
keys. Where a list answers "what is at position 3?", a dict
answers "what is filed under "Ada"?".
10.1 Writing a dict
A dict is written like a list, in square brackets, with
key: value where a list has an item. An empty dict is
[:]:
let ages = ["Ada": 36, "Alan": 41]
let seen: dict[str, int] = [:]
print(ages, seen, len(ages))["Ada": 36, "Alan": 41] [:] 2
Its type is written dict[str, int]: the type of the
keys, then the type of the values. As with a list, Zeno works it out
from what is written, and an empty dict needs it written.
In Zeno a pair of braces is always a block of code, and a pair of
square brackets always holds values, so nobody reading a line has to
work out which a bracket is. {} after if ready
could be read either way in a language that used braces for both.
[:] is the empty dict because the colon is what makes a
dict a dict. (Decision 6.29.)
10.2 Keys and values
A key is a str or an int. All the keys of
one dict are of one type, and so are all its values:
let meanings = [404: "not found", 200: "ok"]
print(meanings[200])ok
let mixed = ["a": 1, 2: 3]error: the keys of a dict are all of one type. This one is int, and the ones before it are str
--> main.zeno:1:22
|
1 | let mixed = ["a": 1, 2: 3]
| ^
1 error found. Nothing was run.
A key has to compare exactly. 0.1 + 0.2 is not
0.3, so a value filed under one float could never be found
under the other: a float key is a mistake the language can simply not
offer. A list or an object can change while it is a key, and would then
be filed in the wrong place. (Decision 6.31.)
A value can be anything a list can hold: numbers, text, lists, objects, other dicts. What is under a key is the thing itself, not a copy, so changing it changes what is in the dict:
let readings: dict[str, list[float]] = [:]
readings["volt"] = [12.0]
readings["volt"].append(12.5)
print(readings)["volt": [12.0, 12.5]]
The one thing a value cannot be is none, for a reason
that comes up below with get.
10.3 Reading
There are three ways to ask a dict about a key, and each says what the program knows:
| Written | Means | If the key is not there |
|---|---|---|
d[key] |
it is there | a KeyError |
d.get(key) |
it may not be | none |
d.get(key, instead) |
it may not be | instead |
key in d |
is it there? | false |
let ages = ["Ada": 36, "Alan": 41]
print(ages["Ada"], "Bob" in ages, ages.get("Bob"), ages.get("Bob", 0))36 false none 0
let ages = ["Ada": 36]
print(ages["Bob"])error: uncaught KeyError: this dict has no key "Bob"
--> main.zeno:2:7
|
2 | print(ages["Bob"])
| ^
get with one argument may give none, so its
answer must be tested before it is used as a number, exactly as with
find. That is why a value cannot itself be
none: in a dict of int or none, a
none from get could mean either "no such key"
or "the key is there and holds none", and no program could tell
which.
let scores: dict[str, int or none] = [:]error: a value of a dict cannot be `int or none`: `get` gives `none` for a key that is not there, and that could not be told from a value that is `none`. Make it a `dict[..., int]`, and leave the key out where there is no value
--> main.zeno:1:1
|
1 | let scores: dict[str, int or none] = [:]
| ^
1 error found. Nothing was run.
Leaving the key out says the same thing with what is already there.
d[key] does not give none for a missing
key, because then every read would be an int or none to
test first, even when the key was stored on the line above. Nor does it
give 0, which would invent a value nobody stored and turn a misspelt key
into a wrong total. (Decision 6.34.)
10.4 Storing and taking out
d[key] = value stores a value: a new key is added, and a
key that is there gets the new value. pop(key) takes a key
out and gives back its value. clear() empties the dict.
let ages = ["Ada": 36, "Alan": 41]
ages["Grace"] = 85
ages["Ada"] = 37
print(ages)
print(ages.pop("Alan"), ages)
ages.clear()
print(ages)["Ada": 37, "Alan": 41, "Grace": 85]
41 ["Ada": 37, "Grace": 85]
[:]
The commonest use of a dict is counting, and it is one line:
let words = "the cat and the hat and the bat".split()
let counts: dict[str, int] = [:]
for word in words {
counts[word] = counts.get(word, 0) + 1
}
print(counts)["the": 3, "cat": 1, "and": 2, "hat": 1, "bat": 1]
The same key written twice in one dict is surely a slip, so it is refused:
let limits = ["low": 1, "low": 2]error: this key is written twice in the dict. A dict has each key once, so the second would replace the first. Take one of them out
--> main.zeno:1:25
|
1 | let limits = ["low": 1, "low": 2]
| ^
1 error found. Nothing was run.
10.5 Order
A dict remembers the order its keys were first stored in. Printing
it, looping over it, keys() and values() all
follow that order, and storing under a key that is there does not move
it.
It is the one order a reader can predict from the program, and it is the same on every run, in every engine and in every build. The order a hash table happens to have would differ between them. (Decision 6.33.)
10.6 Looping over a dict
A loop with one name is given the keys. A loop with two names is given each key and the value under it, following the rule for every loop: the second name is what is at the first.
let stock = ["apples": 4, "pears": 0, "figs": 12]
for fruit in stock {
print(fruit)
}
for fruit, count in stock {
if count == 0 {
print("out of", fruit)
}
}
print(stock.keys(), stock.values())apples
pears
figs
out of pears
["apples", "pears", "figs"] [4, 0, 12]
As with a list, the loop goes through the keys as they were when it
began, so the body may store into the dict and take keys out.
keys() and values() give new lists that are
the caller’s own.
10.7 Equal dicts
Two dicts are equal when they have the same keys with the same
values. The order does not matter here: it says how a dict was built,
and == asks what it holds.
print(["x": 1, "y": 2] == ["y": 2, "x": 1])true
10.8 Every method of a dict
| Written | Does |
|---|---|
d[key] |
the value under key; a
KeyError if it is not there |
d[key] = value |
stores value under
key |
key in d |
whether key is there |
len(d) |
how many keys there are |
d.get(key) |
the value, or none |
d.get(key, instead) |
the value, or instead |
d.pop(key) |
takes the key out and gives its value |
d.keys(),
d.values() |
new lists of the keys and of the values, in order |
d.clear() |
takes every key out |
A dict files values of one type under keys of one type, a
str or an int. It is written
["key": value], empty [:], with the type
dict[str, int]. d[key] expects the key to be
there, get does not, and in asks. A dict keeps
the order its keys arrived in, and a loop with two names is given each
key and its value.
Count the letters in a sentence, then print them in the order they first appeared.
Build a dict from a name to a list of marks, add three marks for each of two names, and print each name with the average of its marks.
Turn a
dict[str, int]round, so that the values become keys. What should happen when two keys have the same value?Write a dict with a key that is a float, and read the message.