Lesson 2 of 12 · 32 min · Grades 9–12
Dictionaries — labelled records
A phone contact is not a nameless pile of numbers. It is a record: name, class, house. A dictionary maps keys to values — column headers in a register. Lists are for “many of the same kind”. Dicts are for “one thing with named fields”.
Student diary
Dictionaries label each field.
You will be able to
- ✓ Create a dict with string keys
- ✓ Read and update a field
- ✓ Know when to use a dict instead of a list
Keys are labels, not positions
student["house"] reads the house field. You do not remember that house was the third item. That is why dicts beat parallel lists (names[i], houses[i]) which go out of sync the moment you sort one of them.
Keys are usually strings. Values can be numbers, strings, even lists. student["house"] = "Blue" updates in place — the same bag, new contents.
Missing keys
Asking for a key that does not exist is an error in real Python. Design the record first: which fields must always exist? Fill them at creation time: {"name": "Meera", "class": 10, "house": "Green"}.
A list of dicts is a table: each dict is a row. That shape is how CSV files, databases and JSON APIs think. You will meet it again in the JSON lesson and in pandas at Advanced level.
Words that matter
- Dictionary
- A mapping of keys to values, written with { }.
- Key
- The label you look up, often a string.
Common mistakes
Avoid: Using student(0) like a list.
Do this: Use student["name"] with the key.
Example program — One student record
Change the house and Run. The name field stays.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Your turn — Lab locker
Make locker with key item set to microscope. Print a line containing microscope.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Self-assessment
Check your understanding before you mark the lesson complete.
Progress is stored in a browser cookie on this device.