Lists
Ordered and changeable
Key → value pairs
Unit 3 · Data Structures
A data structure organizes values so a program can find and work with them. Explore four built-in Python structures and use each lab to see how its rules affect real data.
Ordered and changeable
Ordered and fixed
Unique values
Key → value lookup
Keyed lookup · changeable · insertion order preserved
A dictionary maps each unique key to a value. Instead of remembering that the course is at position 1, a program can ask for record["course"]. Keys must be unique and hashable.
Think of a student record: the field name is the key, and the stored detail is its value. A label such as “semester” is clearer than an unexplained number in a sequence.
Search a field, change its value, or remove it. The record below updates immediately.
Look up a key, update its value, or remove the pair.
record[key]Get a value; missing keys raise KeyError.
record.get(key)Look up safely; returns None if missing.
record[key] = valueAdd a key or replace its value.
student_record = {
"student": "Mira",
"course": "Python",
"semester": "2"
}
print("Value:", student_record.get("course", "Key not found"))Output
Your program's output will appear here.
NameError: name 'mark' is not defined
NameError: A name was used before Python could find a variable or function with that name.
IndexError: list index out of range
IndexError: The requested position is outside the items in this list or sequence.
KeyError: 'email'
KeyError: That key does not exist in this dictionary.
TypeError: can only concatenate str (not "int") to str
TypeError: This operation does not work with the kind of value it received.
ZeroDivisionError: division by zero
ZeroDivisionError: A number cannot be divided by zero.
SyntaxError: invalid syntax
SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.
IndentationError: expected an indented block
IndentationError: The spaces at the start of a line do not match Python's block structure.
get() when the key may not exist.record["student"] retrieves a value; braces create the dictionary.1. How do you retrieve the value stored under the key 'course'?
2. What does assigning a value to an existing dictionary key do?
Ask two questions: does order matter, and should the collection change after creation?
| Structure | Ordered? | Changeable? | Access values by |
|---|---|---|---|
| list | Yes | Yes | Position (index) |
| tuple | Yes | No | Position (index) |
| set | No guaranteed order | Yes | Membership, not index |
| dict | Insertion order is preserved | Yes | Key |
Use a list for a sequence that changes, a tuple for a fixed record, a set for unique membership, and a dictionary for named lookups.