What you will learn
- Create and access dictionaries.
- Add, update, and remove key-value pairs.
- Use
get()for safer lookups. - Iterate over keys, values, and items.
The code from this chapter
Type these programs yourself. The predictions below are the exercises; the explanations are in the book.
10.1 A Dictionary Maps Keys to Values
TPRM Lab 10.1: Create a Record
Type this into a file, predict the output, then run it.
student = {
"name": "Alex",
"age": 20,
"grade": 87
}
print(student["name"])
print(student["grade"])
print(len(student))
10.2 Missing Keys
Type this into a file, predict the output, then run it.
student = {"name": "Alex", "grade": 87}
print(student.get("name"))
print(student.get("email"))
print(student.get("email", "Not provided"))
10.3 Iterate Through a Dictionary
TPRM Lab 10.3: Three Iteration Patterns
Type this into a file, predict the output, then run it.
prices = {"apple": 1.25, "banana": 0.75, "pear": 1.10}
for item in prices:
print(item)
for price in prices.values():
print(price)
for item, price in prices.items():
print(item, price)
10.4 A Word Counter
Type this into a file, predict the output, then run it.
text = "red blue red green blue red"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)