Dictionaries & Sets
5. Dictionaries & Sets
5.1Key-Value Pairs (Dictionaries)
Think of a real-world dictionary — you look up a word (the key) to find its definition (the value). Or think of a phone contact list!
SHOW:
WHAT HAPPENED HERE
{} with key: value pairs. We retrieved values using key names inside square brackets: user["name"].THE TECHNICAL NAME
TAKEAWAY
{"key": "value"}.5.2Safely Reading & Updating Dictionaries
If you look up a missing key with dict["missing"], Python raises an error. But there's a safer way!
SHOW:
WHAT HAPPENED HERE
.get("email", default) safely returned "Not provided" instead of crashing. Then profile["status"] = "Active" added a new key-value pair.THE TECHNICAL NAME
TAKEAWAY
.get() for safe lookups and dict[key] = value to update.5.3Unique Collections (Sets)
Think of a bag of lottery balls — every ball has a distinct number, and duplicates are impossible.
SHOW:
WHAT HAPPENED HERE
THE TECHNICAL NAME
TAKEAWAY
{"a", "b"} automatically remove duplicate items.5.4Set Operations (Union & Intersection)
Think of comparing two friend lists to find mutual friends (overlap) or combining all friends into one party invite list.
SHOW:
WHAT HAPPENED HERE
& operator found common items (intersection). The | operator combined all unique items (union).THE TECHNICAL NAME
&), and combining sets is union (|).TAKEAWAY
& to find shared items and | to combine sets.GOTCHA 1
KeyError when accessing a non-existent dictionary key directly with dict[key] instead of dict.get(key).
GOTCHA 2
Expecting set elements to maintain insertion order (sets are unordered).
GOTCHA 3
Using a mutable list as a dictionary key (keys must be immutable).
WHERE THIS SHOWS UP IN REAL CODE
Web APIs return JSON data formatted as dictionaries, while unique user IDs and tag filters use sets.
TRY THIS YOURSELF
Create a dict student = {'name': 'Sam', 'grade': 'A'}, add 'age': 20, and print student.keys().
Observe how get() returns default value without crashing.
Demonstrate dictionary key-value access, safe get(), set uniqueness, and set operations.
What syntax creates a Python dictionary?
What happens when accessing a non-existent key with `dict['missing']`?
Why is `dict.get('key', default)` safer than `dict['key']`?
What is a main characteristic of a Python set?
Which set operator calculates the intersection (common items) of two sets?
What does `user.keys()` return?
Can a mutable list be used as a dictionary key?
What is the result of `set([1, 1, 2, 3, 3])`?
Which method returns key-value tuples from a dictionary?
# comments · dicts-sets
- @priya · 2h ago
The typewriter hero is such a nice touch.
- @alex · 1h ago
Totally agree! Made it super engaging.
- @sam · 1d ago
Finally a course where I can run code without leaving the page.