loop
Tuples and dictionaries

Module 4 · Tuples and dictionaries · Lesson 5 of 6

Tuples and dictionaries together

Here's where the last two lessons click together. You saw that items() hands back (key, value) tuples. You saw that a tuple can be unpacked into separate variables. Put them side by side and the most common dictionary loop falls right out.

x, y = point
point =(3, 4)
x3
y4

The same trick powers the one-line swap a, b = b, a — pack on the right, unpack on the left.

When you write for name, age in ages.items(), each round hands you one (key, value) tuple and unpacks it into name and age — exactly the move above, happening once per entry.

Run it yourselfruns in your browser · Python
main.py

The partnership runs the other way too. Because tuples are immutable, they can serve as dictionary keys — something a list can never do — which is perfect for things like a lookup keyed by a pair of cities. And a list of tuples drops straight into dict() to build a dictionary.

Run it yourselfruns in your browser · Python
main.py

Immutable tuples and flexible dictionaries turn out to be natural partners: one provides safe, fixed groupings; the other looks them up by name. A quick quiz to lock the whole section in.