Looking Things Up Instead of Counting Along
A list makes you remember where something is. A dictionary lets you forget. Build one from scratch, look something up by name instead of position, and ask for a key that was never there.
A list makes you remember where something is. A dictionary lets you forget. Build one from scratch, look something up by name instead of position, and ask for a key that was never there.
Looking up by name instead of position
A list of prices tells you nothing unless you already remember that index 0 is apples. A dictionary stores the name alongside the value, and you look up by that name directly.
$ >>> prices = {"apple": 0.60, "banana": 0.35}$ >>> prices["banana"]$ 0.35Each entry is a key and a value. The key is what you look up with; the value is what you get back. Keys are unique — assign to a key that already exists, and you overwrite the value, you do not add a second entry.
Look something up by key:
>>> prices['apple']
'0.60'
A missing key is not zero, it is an error
Ask for a key that is not there, and Python does not return None or 0 to be helpful. It raises KeyError and stops the program, the same way an undefined variable would.
$ >>> prices["mango"]$ KeyError: 'mango'When a dictionary is the right tool, and when a list still is
Reach for a dictionary when you look things up by a meaningful name — a username, a product code, a configuration setting. Reach for a list when what matters is order and position — a queue of tasks, a sequence of moves, anything where first and next mean something.
Key takeaways
- A dictionary stores key/value pairs and looks up by key, not by position.
- Assigning to an existing key overwrites its value — keys never repeat.
- A missing key raises KeyError. Use .get() when a missing key is a normal, expected outcome.
- Choose a dictionary when you look things up by name; choose a list when order and position matter.