Dictionaries and key-value lookup
A dictionary maps each unique key to an associated value, making lookup by a meaningful label direct.
Learning objectives
- Create a dictionary and retrieve a value by key.
- Handle a missing key intentionally.
Mapping a label to data
PYTHON
student = {"name": "Asha", "score": 86}
print(student["name"])
score = student.get("score", 0)Here "name" and "score" are keys. Bracket lookup raises KeyError if the key is absent. get instead returns a supplied default—in this example, 0—when the key is missing.
Common mistakes
- Keys must be hashable; mutable lists cannot be dictionary keys.
- Do not rely on a key appearing when data comes from an incomplete external source—choose a default or validate it.
Applications and references
Dictionaries model JSON-like records, configuration, lookup tables, and counts.