Ce livre n’est pas encore disponible en Français. Éditions : English.
Primary & Middle School Computer Science · Du CP à la 3e
26Dictionaries
Lina has two hundred contacts in her phone. She types “Grandma”, and the number appears at once. The phone does not read the list from the top, checking each name in turn: it looks the name up. Python has a kind of value made for looking things up by name.
You already know
A list keeps values in order and is reached by index, from 0 (Chapter 20); finding an item in it means walking through it. A string can be cut into words with split (Chapter 21).
26.1 Looking a value up by its key
Definition 26.1 (Dictionary, key, entry)
A dictionary is a value that holds pairs: each pair, an entry, links a key to a value. The keys are all different; d[key] gives the value linked to key. A dictionary is written between braces, with a colon between each key and its value: {"Sami": 12, "Noor": 13}.
phone = {"Grandma": "0612 345 678", "Sami": "0698 765 432", "Noor": "0655 501 020"}
print(phone["Grandma"])
print(len(phone), "contacts")
print("Leo" in phone, "Sami" in phone)
$ python contacts.py
0612 345 678
3 contacts
False True
in tests whether a key is there.Asking for a key that is not there is a runtime error, a KeyError:
phone = {"Grandma": "0612 345 678", "Sami": "0698 765 432"}
print(phone["Leo"])
$ python key_error.py
Traceback (most recent call last):
File "~/session/key_error.py", line 2, in <module>
print(phone["Leo"])
~~~~~^^^^^^^
KeyError: 'Leo'
[exit status 1]
Either test first with in, or use get, which returns a default value instead of stopping:
phone = {"Grandma": "0612 345 678", "Sami": "0698 765 432"}
for name in ["Sami", "Leo"]:
print(name, phone.get(name, "not in the contacts"))
get with a default. code/grade-8/02-dictionaries/listings/get_default.py$ python get_default.py
Sami 0698 765 432
Leo not in the contacts
26.2 Creating, changing, walking through
An assignment to d[key] adds an entry if the key is new, and changes its value if the key is already there; del d[key] removes an entry. A for loop over a dictionary walks through its keys, in the order in which they were added. d.items() gives the key and the value together: the loop then has two variables, separated by a comma.
stock = {"apples": 12, "pears": 5}
stock["plums"] = 20 # a new key: a new entry
stock["apples"] = 9 # a key already there: its value changes
del stock["pears"]
print(stock)
for fruit in stock:
print(fruit, stock[fruit])
for fruit, count in stock.items():
print(fruit, "->", count)
$ python change_walk.py
{'apples': 9, 'plums': 20}
apples 9
plums 20
apples -> 9
plums -> 20
Python keeps a dictionary in the order of its keys’ arrival; changing a value does not move its key, which is why apples is still first.
26.3 Counting with a dictionary
A dictionary of counts answers “how many of each?”. For each item, its count is its old count plus one, and get(item, 0) gives 0 for an item not seen before:
counts[word] = counts.get(word, 0) + 1
text = "the fox and the hen"
counts = {}
for ch in text:
if ch != " ":
counts[ch] = counts.get(ch, 0) + 1
print(counts)
print("e appears", counts["e"], "times")
$ python count_letters.py
{'t': 2, 'h': 3, 'e': 3, 'f': 1, 'o': 1, 'x': 1, 'a': 1, 'n': 2, 'd': 1}
e appears 3 times
The same pattern counts words. This version prints the dictionary after each word, to show it grow:
sentence = "the fox saw the hen and the hen saw the fox"
counts = {}
for word in sentence.split():
counts[word] = counts.get(word, 0) + 1
print(word, counts)
$ python count_words.py
the {'the': 1}
fox {'the': 1, 'fox': 1}
saw {'the': 1, 'fox': 1, 'saw': 1}
the {'the': 2, 'fox': 1, 'saw': 1}
hen {'the': 2, 'fox': 1, 'saw': 1, 'hen': 1}
and {'the': 2, 'fox': 1, 'saw': 1, 'hen': 1, 'and': 1}
the {'the': 3, 'fox': 1, 'saw': 1, 'hen': 1, 'and': 1}
hen {'the': 3, 'fox': 1, 'saw': 1, 'hen': 2, 'and': 1}
saw {'the': 3, 'fox': 1, 'saw': 2, 'hen': 2, 'and': 1}
the {'the': 4, 'fox': 1, 'saw': 2, 'hen': 2, 'and': 1}
fox {'the': 4, 'fox': 2, 'saw': 2, 'hen': 2, 'and': 1}
the changes a count instead of adding a key.26.4 A record as a dictionary, a table as a list of records
Definition 26.2 (Record and field)
A record is a group of values that describe one thing, each under a name: a field. In Python, a record can be a dictionary whose keys are the field names.
A book of a school library has a title, an author and a year: three fields. A list of such records is a table, one record per row.
books = [
{"title": "The Lighthouse Cat", "author": "Mara Quill", "year": 1998},
{"title": "Seven Bridges", "author": "Tom Alder", "year": 2011},
{"title": "Rain on Hilltop", "author": "June Okafor", "year": 2004},
]
for book in books:
print(book["year"], book["title"], "by", book["author"])
recent = 0
for book in books:
if book["year"] > 2000:
recent = recent + 1
print(recent, "of", len(books), "books are from after 2000")
$ python books.py
1998 The Lighthouse Cat by Mara Quill
2011 Seven Bridges by Tom Alder
2004 Rain on Hilltop by June Okafor
2 of 3 books are from after 2000
26.5 Exercises
Exercise 26.1 ★
With d = {"a": 1, "b": 2, "c": 3}, what is d["b"]? What does d["d"] do?
Exercise 26.2 ★
d is the empty dictionary {}. After d["x"] = 1 and then d["x"] = 5, what are len(d) and d["x"]?
Solution
Solution of Exercise 26.2.
The second assignment changes the value of the key "x", which is already there: len(d) is 1 and d["x"] is 5.
Exercise 26.3 ★
What does this program print?
ages = {"Sami": 12, "Noor": 13, "Leo": 12}
for name, age in ages.items():
if age == 12:
print(name)
items(). code/grade-8/02-dictionaries/exercises/walk_items.pySolution
Solution of Exercise 26.3.
Sami, then Leo: the two names whose age is 12, in the order of the dictionary.
Exercise 26.4 ★
Write a function capital(country) that looks a country up in a dictionary of four capitals and returns "not known" for any other country.
Solution
Solution of Exercise 26.4.
capitals = {"France": "Paris", "Italy": "Rome", "Japan": "Tokyo", "Kenya": "Nairobi"}
def capital(country):
return capitals.get(country, "not known")
print(capital("Japan"), "/", capital("Peru"))
It prints Tokyo / not known.
Exercise 26.5 ★★
This program stops with KeyError: 'mouse'. Fix it so that a word missing from the dictionary is kept as it is.
french = {"the": "le", "cat": "chat", "eats": "mange", "fish": "poisson"}
sentence = "the cat eats the mouse"
words = []
for word in sentence.split():
words.append(french[word])
print(" ".join(words))
Solution
Solution of Exercise 26.5.
french[word] needs every word to be a key. With french.get(word, word), a missing word gives itself back:
for word in sentence.split():
words.append(french.get(word, word)) # unknown words stay as they are
print(" ".join(words))
It prints le chat mange le mouse.
Exercise 26.6 ★★
This program should count the words of "a rose is a rose". It prints {'a': 1, 'rose': 1, 'is': 1}. Why? Fix it.
counts = {}
for word in "a rose is a rose".split():
counts[word] = 1
print(counts)
Solution
Solution of Exercise 26.6.
counts[word] = 1 sets the count to 1 each time, so a word seen twice still counts 1. The counting pattern adds one to the old count: counts[word] = counts.get(word, 0) + 1, which gives 2 for a and for rose.
Exercise 26.7 ★★
Write a function most_frequent(sentence) that returns the word that appears most often.
Solution
Solution of Exercise 26.7.
Count the words, then keep the best so far:
def most_frequent(sentence):
counts = {}
for word in sentence.split():
counts[word] = counts.get(word, 0) + 1
best = ""
for word in counts:
if best == "" or counts[word] > counts[best]:
best = word
return best
print(most_frequent("the fox saw the hen and the hen saw the fox"))
It prints the, which appears four times.
Exercise 26.8 ★★
Write a function invert(d) that swaps the keys and the values of a dictionary whose values are all different. Why must they be different?
Solution
Solution of Exercise 26.8.
def invert(d):
"""Swap keys and values; the values must all be different."""
result = {}
for key, value in d.items():
result[value] = key
return result
print(invert({"one": 1, "two": 2, "three": 3}))
The values become keys, and keys are all different: if two keys had the same value, the second entry would replace the first in the result.
Exercise 26.9 ★★
Without running it, how many entries does a word-count dictionary have for "a rose is a rose is a rose"? What are the counts?
Solution
Solution of Exercise 26.9.
Three entries: a 3, rose 3 and is 2.
Exercise 26.10 ★★★
Write a function oldest(books) that returns the record of the oldest book of a list like the one of Listing 26.7.
Solution
Solution of Exercise 26.10.
def oldest(books):
best = books[0]
for book in books:
if book["year"] < best["year"]:
best = book
return best
print(oldest(books)["title"])
It prints The Lighthouse Cat (1998).
Exercise 26.11 ★★★
Votes for candidates are written on ballots. One method counts each candidate’s votes by walking all the ballots; the other walks the ballots once with a dictionary of counts. How many names does each method look at? Which is better for 1 000 ballots and 50 candidates, and by how much?
Solution
Solution of Exercise 26.11.
The first method walks the ballots once per candidate: names. The second walks them once: names. For 1 000 ballots and 50 candidates, 50 000 against 1 000: the dictionary looks at 50 times fewer names, as many times fewer as there are candidates.
Exercise 26.12 ★★★
Write a function group_by_first_letter(words) that returns a dictionary whose keys are first letters and whose values are lists of the words that start with each.
Solution
Solution of Exercise 26.12.
A word whose first letter is new starts an empty list first:
def group_by_first_letter(words):
groups = {}
for word in words:
first = word[0]
if first not in groups:
groups[first] = []
groups[first].append(word)
return groups
print(group_by_first_letter(["apple", "bean", "avocado", "cherry", "banana"]))
It prints {'a': ['apple', 'avocado'], 'b': ['bean', 'banana'], 'c': ['cherry']}.
26.6 Problem: Counting the Votes
Problem 26.1
Weekend problem — two ways to count an election
A class of 40 pupils elects its delegate among six candidates. Each pupil writes one name on a ballot, and the ballots are kept in a list.
"""The ballots of the weekend problem: 40 for 6 candidates, then 400 for 20."""
CANDIDATES = ["Ada", "Ben", "Chloe", "Dev", "Eva", "Femi"]
BALLOTS = [
"Chloe", "Ada", "Eva", "Chloe", "Ben", "Dev", "Chloe", "Ada", "Femi", "Eva",
"Chloe", "Dev", "Ada", "Chloe", "Eva", "Ben", "Ada", "Chloe", "Dev", "Eva",
"Femi", "Chloe", "Ada", "Eva", "Chloe", "Ben", "Dev", "Ada", "Chloe", "Eva",
"Ada", "Femi", "Chloe", "Eva", "Dev", "Ada", "Chloe", "Ben", "Eva", "Ada",
]
def many_ballots(count, candidates):
"""A longer, made-up election: ballot i goes to the candidate a fixed rule picks."""
ballots = []
for i in range(count):
ballots.append(candidates[(i * i + 3 * i) % len(candidates)])
return ballots
Part I — By hand.
- Tally the first 12 ballots by hand. Who leads?
- How did you keep the counts? What would you do with a name not yet on your tally?
Part II — Two programs. The first program counts each candidate’s votes with a walk through all the ballots. A function may return two values separated by a comma; the caller receives them the same way, results, looked_at = ....
from ballots import BALLOTS, CANDIDATES
def count_per_candidate(ballots, candidates):
"""For each candidate, walk all the ballots. Also count the names looked at."""
results = []
looked_at = 0
for name in candidates:
votes = 0
for ballot in ballots:
looked_at = looked_at + 1
if ballot == name:
votes = votes + 1
results.append(votes)
return results, looked_at
if __name__ == "__main__":
results, looked_at = count_per_candidate(BALLOTS, CANDIDATES)
for i in range(len(CANDIDATES)):
print(CANDIDATES[i], results[i])
print("names looked at:", looked_at)
- What does
looked_atcount? How often does the inner loop run? - Run it. Who wins, and how many names were looked at?
The second program walks the ballots once:
from ballots import BALLOTS
def count_once(ballots):
"""Walk the ballots once, with a dictionary of counts."""
counts = {}
looked_at = 0
for ballot in ballots:
looked_at = looked_at + 1
counts[ballot] = counts.get(ballot, 0) + 1
return counts, looked_at
def winner_and_margin(counts):
best = ""
for name in counts:
if best == "" or counts[name] > counts[best]:
best = name
second = 0
for name in counts:
if name != best and counts[name] > second:
second = counts[name]
return best, counts[best] - second
if __name__ == "__main__":
counts, looked_at = count_once(BALLOTS)
print(counts)
winner, margin = winner_and_margin(counts)
print("winner:", winner, "by", margin, "votes")
print("names looked at:", looked_at)
- Which line is the counting pattern of this chapter?
- How does
winner_and_marginfind the second best? - Run it. Do both programs agree? How many names were looked at now?
- Why does the dictionary list the candidates in a different order from
CANDIDATES?
Part III — A larger election. A third program runs both methods on the class, then on a made-up election of 400 ballots for 20 candidates:
from ballots import BALLOTS, CANDIDATES, many_ballots
from votes_dict import count_once
from votes_list import count_per_candidate
def compare(ballots, candidates):
results, by_list = count_per_candidate(ballots, candidates)
counts, by_dict = count_once(ballots)
print(len(ballots), "ballots,", len(candidates), "candidates:", by_list,
"names looked at with lists,", by_dict, "with a dictionary")
names = []
for i in range(20):
names.append("C" + str(i + 1))
compare(BALLOTS, CANDIDATES)
compare(many_ballots(400, names), names)
- Predict the four numbers before running it.
- Run it. Write a rule for each method in terms of the number of ballots and of candidates .
- A country votes with 40 million ballots for 12 lists. How many names would each method look at?
- State the result.
Solution
Solution of Problem 26.1.
1. Chloe 4, Ada 2, Eva 2, Dev 2, Ben 1, Femi 1: Chloe leads.
2. One tally line per name, added the first time the name appears: exactly what a dictionary of counts does.
3. Every name looked at; the inner loop runs once per ballot, for each of the six candidates.
4. Chloe wins:
$ python votes_list.py
Ada 9
Ben 4
Chloe 11
Dev 5
Eva 8
Femi 3
names looked at: 240
5. counts[ballot] = counts.get(ballot, 0) + 1.
6. It walks the counts again and keeps the largest count of any name other than the winner; the margin is the difference.
7. They agree, with 40 names looked at instead of 240:
$ python votes_dict.py
{'Chloe': 11, 'Ada': 9, 'Eva': 8, 'Ben': 4, 'Dev': 5, 'Femi': 3}
winner: Chloe by 2 votes
names looked at: 40
8. A key enters the dictionary when its name first appears on a ballot: Chloe is on the first ballot, Ada on the second.
9. and 40; and 400.
10.
$ python votes_compare.py
40 ballots, 6 candidates: 240 names looked at with lists, 40 with a dictionary
400 ballots, 20 candidates: 8000 names looked at with lists, 400 with a dictionary
The list method looks at names, the dictionary at .
11. 480 million names with lists, 40 million with a dictionary.
12. Result. Counting with one walk per candidate looks at candidates ballots names (240 for the class, 8 000 for the larger election); counting with a dictionary looks at each ballot once (40, then 400).