loop
Tuples and dictionaries

Module 4 · Tuples and dictionaries · Lesson 3 of 6

Dictionaries

Lists and tuples find things by position. A dictionary finds them by name. Each entry is a key paired with a value, written key: value inside curly braces — and you reach a value by handing over its key.

ages["Alan"]
ages = {
"Ada"36
"Alan"41
"Grace"29
}
→ 41

That's the whole idea: ages["Alan"] goes straight to Alan's value, no counting required. Keys are usually strings (they must be unique and immutable — a string or a tuple works, a list does not), and the values can be anything at all.

Run it yourselfruns in your browser · Python
main.py

Assigning to a key either changes it if it exists or adds it if it doesn't, and del removes a pair. The one sharp edge: asking for a key that isn't there raises a KeyError — which is exactly what the dictionary methods coming next help you avoid.