Looping over a dict
Data travels in pairs and small fixed groups constantly: a point's (x, y), a row's (name, score), and every entry of a dict. This lesson covers the loop that processes a whole dict and the tuple, Python's type for those fixed little groups, together, because dict iteration hands you tuples.
Three views of a dictionary, three loops:
for name in ages: # keys (the default) for age in ages.values(): # values only for name, age in ages.items(): # pairs: the one you will use most
That two-variable form works because .items() hands out each pair as a tuple.
Tuples: sequences that never change
A tuple is written with parentheses: point = (3, 4). Index and slice it like a list, but it is immutable: point[0] = 9 is a TypeError. Use tuples for small fixed records where each position means something, like (x, y) or (name, score).
Unpacking splits a tuple into variables in one line, and it is why the .items() loop reads so well:
x, y = (3, 4) # x is 3, y is 4 a, b = b, a # the classic swap, no temp variable
Code exercise · python
Run this. The loop unpacks each (key, value) tuple straight into `name` and `age`.
Quiz
What happens when you run `t = (1, 2, 3)` and then `t[0] = 99`?
Code exercise · python
Your turn. `cart` is a list of (item, quantity) tuples. Loop over it with unpacking and print each line like `apple: 3`. Then print the total quantity.
Code exercise · python
One more, converting a list of pairs into a dict, a shape change you will perform constantly with real data. Loop over `cart` with unpacking and store each quantity under its item name in `stock`, then print stock and the quantity of banana.