Module 4 · Tuples and dictionaries · Lesson 4 of 6
Dictionary methods and functions
A dictionary comes with a small, well-chosen toolkit. Three methods let you view its contents in different shapes — keys(), values() and items() — and they're exactly what you reach for when looping.
ages = {"Ada": 36, "Alan": 41, "Grace": 29}keys() gives you the names, values() the data, and items() both together as (key, value) tuples — a detail that becomes important in the next lesson.
The other two tools are about looking things up safely. Remember that ages["Nobody"] crashes with a KeyError. The in operator checks whether a key exists first, and get() fetches a value but politely returns None (or a default you choose) when the key is missing.
Note that in always tests the keys, never the values — the natural question for a dictionary is “do you have this key?” With the toolkit in hand, let's see tuples and dictionaries join forces.