Chapter 9
Dictionaries and Other Collections
Give Each Value a Label
A 0, the second at index 1, and so on.
That becomes awkward when the values are different facts about one thing.
book = ["Kindred", "Octavia E. Butler", 1979]
What does position 1 mean? You have to remember. Someone reading book[1] has to search for the list’s definition or trust a comment.
You could split the facts into
title = "Kindred"
creator = "Octavia E. Butler"
year = 1979
That is clear for one book. For twenty books, you need twenty sets of variable names.
A record with labels
A
book = {
"title": "Kindred",
"creator": "Octavia E. Butler",
"year": 1979,
}
Each key labels the meaning of its value:
| Key | Value |
|---|---|
"title" | "Kindred" |
"creator" | "Octavia E. Butler" |
"year" | 1979 |
Instead of asking for a position, you ask for a key:
print(book["creator"])
The brackets look like list indexing, but the lookup is different. A list answers, “What is at position 1?” A dictionary answers, “What value is stored under the key "creator"?”
Keys must be unique
A dictionary can store many values, but each key appears only once. If you
book["year"] = 1988
The dictionary still has one "year" key. Its value is now 1988.
Values do not need to be unique. Two different keys can both hold "unknown".
Dictionaries are mutable
Like a list, a dictionary can change after it is created. You can:
add a new key-value pair;
replace the value for an existing key;
remove a pair;
read and
through its contents.
This chapter concentrates on adding, changing, reading, and looping. Chapter 10 will return to the errors that can happen when a program asks for a missing key.
Model the information, not its display
The dictionary holds facts:
book = {
"title": "Kindred",
"creator": "Octavia E. Butler",
"year": 1979,
}
A
def book_label(book):
return f"{book['title']} by {book['creator']}"
That separation uses the function design from Chapter 8. The dictionary models the record. The function performs an operation with it.
What does this program print?
place = {
"name": "Kyoto",
"country": "Japan",
}
print(place["country"])
Which information is most naturally modeled as one dictionary?