Dictionaries and Other Collections · practice
Create and Read a Dictionary
A
book = {
"title": "Kindred",
"creator": "Octavia E. Butler",
"year": 1979,
}
Each entry has three parts:
"title": "Kindred"
# key value
A colon separates the key from its
The trailing comma after the final entry is optional. Keeping it makes the dictionary easier to extend and lets every entry follow the same pattern.
Values can have different types
The example holds two
event = {
"name": "Python meetup",
"seats": 40,
"online": False,
}
A dictionary brings related facts together. The values do not need to share a type.
For now, use strings as keys. Python permits some other "title" and "year" make beginner records especially readable.
Read by key
Use square brackets with the exact key:
print(book["title"])
print(book["year"])
This prints:
Kindred
1979
Key spelling and capitalization matter. "title" and "Title" are different keys.
An empty dictionary
Empty curly braces create an empty dictionary:
record = {}
print(type(record))
You will meet sets near the end of the chapter. Sets also use curly braces when they contain values, but {} always means an empty dictionary.
Ask for a key that exists
Bracket lookup expects the key to be present:
book["publisher"]
If "publisher" is missing, Python raises a
Which value is a dictionary with the keys "name" and "score"?
Task
Create a book with exactly these entries:
| Key | |
|---|---|
"title" | "Kindred" |
"creator" | "Octavia E. Butler" |
"year" | 1979 |
Then use three bracket lookups to print the values in this exact order:
Kindred
Octavia E. Butler
1979