Looping over dictionaries

Dictionaries & Sets, lesson 2 of 5

🗂️ 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 keys
  • d.values(): the values
  • d.items(): (key, value) pairs, ready to unpack

Dicts remember the order keys were added.

Example

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
Example

Word counter

Paste in a sentence of your own. Try text.lower().split() so "The" and "the" count together.

Quiz

What does this print?

Example

Best sales day

The same "track the best" pattern from loops, now with key and value together.

Example

Changing size mid-loop

Change the loop to for item in list(stock): and it works.

Quiz

What does this print?

Exercise

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.

Exercise

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.