Dictionaries and Other Collections · practice
Loop Through a Dictionary
A .items() gives you exactly that pair.
ratings = {
"Kindred": 5,
"Earthsea": 5,
"Dune": 4,
}
Ask for each label-value pair
Use .items() when each pass needs both key and value:
for title, rating in ratings.items():
print(f"{title}: {rating}")
Each item is a two-part pair called a title and the second part to rating. This is called unpacking. You only need that recognition-level idea here: .items() supplies a pair, and the two loop names receive its two parts.
You do not need to memorize an abstract rule. Read the loop header as:
For each title and rating in the dictionary’s items…
A plain loop such as for title in ratings: visits only the keys. That is useful sometimes, but it cannot fill both names in this lesson’s loop header. Here we need .items() because the report uses both pieces.
You need both the title and rating on every loop pass. Which loop header fits?
Task
ratings .items().
For every title and rating:
print a line in the form
Kindred: 5;add the rating to
total.
After the loop, print Total: 14.
Expected output:
Kindred: 5
Earthsea: 5
Dune: 4
Total: 14