CPSC 203, 2026 W1
October 15, 2026
Dictionaries / key-value lookup is useful for solving other common problems.
Last two classes: First five patterns.
Today: Translation / mapping.
Use case: Convert values from one representation to another.
Example: Go through a string and replace any word which has an emoji equivalent.
Example: Substitution cypher.
| word | emoji |
|---|---|
| sun | ☀️ |
| rain | 🌧️ |
| cloud | ☁️ |
| happy | 😊 |
| sad | 😢 |
| love | ❤️ |
| cat | 🐱 |
| dog | 🐶 |
| coffee | ☕ |
Open today’s activity. You’ll solve 2 new puzzles.
STUDENT_dict_patterns_nb.py.Dictionaries give you fast lookup by key — whether you have 100 items or 100,000.
| Pattern | Use Case | Technique |
|---|---|---|
| Record | Store named fields | {"name": ..., "age": ...} |
| Membership | Track what we’ve seen | seen[x] = True |
| Counting | Count occurrences | Counter(items) |
| Complement | Find pairs | Store & check complements |
| Grouping | Organize by category | defaultdict(list) |
| Translation | Convert values | Direct key → value mapping |
In CPSC 103 / 110: One code template for each data type.
In CPSC 203:
Remember: Any piece of data in Python is an object that belongs to a class.
You will often see references to methods with two underscore characters before and after the name; for example, __init__(), __str__(), __len()__.
Magic methods are used by Python to implement internal behaviours and operator overloading.
print(x), Python displays the result of x.__str__().len(x), Python returns the result of x.__len__().x + y, Python will call x.__add__(y).x[i], Python will call x.__getitem__(i).x[i] = y, Python will call x.__setitem__(i, y).Remember: Any piece of data in Python is an object that belongs to a class.
When we have a bunch of related classes, we often organize them in a hierarchy.
object class.Conceptually, the idea is that you can work with an object as if it was an instance of the parent class rather than needing to know to which specific child class it belongs.
In particular, different children might:
But the user only needs to know the common method’s signature (typically given in the parent class).
A contract specifying which method(s) a child class should implement.
You can create classes which inherit from / implement an interface.
iterablefor loop over the elements of the object.__iter__(self) method.for item in x: ...list(x) or tuple(x).iterableExamples:
list, tuple, str. Elements will always come out in the same order in which they were created.set. Elements may come out in a different order.dict. The iteration is over the keys, and elements may come out in a different order.range() and enumerate().Series and DataFrames, and many more.hashable__hash__(self) and __eq__(self, other) methods.hashableint, str, bool, float, NoneType.NamedTuples (but not dataclasses).tuple, frozenset, (as of Python 3.15) frozendict.some_type | None.