🗂️ Dictionaries & Sets, lesson 2 of 5
Looping over dictionaries
Walk through keys, values and pairs, and count things with a dict.
11 min
2 exercises
2 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
Looping over a dict gives you its keys. Ask for other views when you need them:
d.keys(): the keysd.values(): the valuesd.items():(key, value)pairs, ready to unpack
Dicts remember the order keys were added.
Report card
Change the loop to for subject in grades:. What do you get?
The counting pattern. To count things, use the
thing as the key and the count as the value.
counts.get(word, 0) returns 0 the first time a
word appears, so there's no KeyError:
counts[word] = counts.get(word, 0) + 1
Word counter
Paste in a sentence of your own. Try text.lower().split() so "The" and "the" count together.
Counting words, one at a time
counts = {} starts empty. The loop visits the 8 words of text one by one.
What does this print?
Best sales day
The same "track the best" pattern from loops, now with key and value together.
Changing size mid-loop
Change the loop to for item in list(stock): and it works.
What does this print?
Checkout total
cart maps each item to a quantity, and
prices maps items to a price. Loop over
cart.items() and add quantity * price for each
item to total.
Lunch vote
Count the votes into the tally dict (food → number
of votes) using the counting pattern. Then set
winner to the food with the most votes.