Chapter 5: Dictionaries and Sets
1. Why learn these two structures?
| Everyday need | Structure that helps |
|---|---|
| Look-up something by a label (e-mail address → name, country code → capital) | Dictionary |
| Keep a bag of unique things (student IDs, tags, lottery numbers) | Set |
2. Dictionaries: the phonebook of Python
- What they are – An unordered, mutable mapping of keys → values.
- Keys must be immutable & unique (str, int, tuple, etc.).
- Values can be anything (even a list or another dict).
student = {"name": "John", "age": 20, "grades": [85, 90, 88]}2.1 Core actions
| Task | Example | Notes |
|---|---|---|
| Read | student['name'] → 'John' | Raises KeyError if missing |
| Safe read | student.get('age', 0) | Gives default instead of error |
| Add / update | student['major'] = 'CS' | Same syntax for both |
| Delete | del student['grades'] | Removes key & its value |
| Membership | 'name' in student → True | Checks keys only |
| Lists of pieces | student.keys(), .values(), .items() | Convert to list() for indexing |
2.2 Looping patterns
for key in student: # keys
...
for val in student.values(): # values
...
for k, v in student.items(): # pairs
...2.3 Dictionary comprehension
squares = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, ...}3. Nested dictionaries = dictionaries inside dictionaries
Great for hierarchical data:
school = {
"students": {
"john": {"age": 20, "major": "CS"},
"alice": {"age": 19, "major": "Math"},
},
"teachers": {
"smith": {"subject": "Python", "years": 5},
}
}
school["students"]["john"]["age"] = 21Tip: walk down one key at a time.
4. Common pitfalls & tips
- Duplicate keys? Last one wins (
{'Monarch': 3, 'Monarch': 2}→ only2). - Prefer
.get()when the key might be missing. - Keys must stay immutable; values can change freely.
5. Sets: bags of unique items
- What they are – An unordered, mutable collection with no duplicates.
- Literals with
{}or useset()for an empty set ({}alone is an empty dict).
set1 = {1, 2, 3}
set2 = {3, 4, 5}5.1 Math-style operations
| Operation | Code | Result (set1={1,2,3}, set2={3,4,5}) | |
|---|---|---|---|
| Union | `set1 | set2` | {1,2,3,4,5} |
| Intersection | set1 & set2 | {3} | |
| Difference | set1 - set2 | {1,2} | |
| Symmetric difference | set1 ^ set2 | {1,2,4,5} |
5.2 Add, remove, test
set1.add(6) # {1,2,3,6}
set1.remove(1) # {2,3,6}
3 in set1 # True5.3 What may go inside? (hashability)
| Allowed | Not allowed |
|---|---|
| Numbers, strings, tuples of immutables | Lists, dicts, other sets, tuples containing mutables |
Python rejects unhashable elements with TypeError, keeping look-ups lightning fast.
6. Mini challenge (from the slides)
Let's look at the get() method first:
Help on built-in function get:
get(key, default=None, /) method of builtins.dict instance
Return the value for key if key is in the dictionary, else default.Now, what is the output of the following code?
d = {3: 33}
d[5] = d.get(4, 12)
d[4] = d.get(3, 8)
print(d)A) {3: 33, 5: 12, 4: 8}
B) {3: 33, 5: 12, 4: 33}
C) {3: 33, 5: 4, 4: 3}
D) Error caused by getThe correct answer is B.
d = {3: 33} # d = {3: 33}
d[5] = d.get(4, 12) # d.get(4, 12) returns 12 since 4 isn't in d
# d = {3: 33, 5: 12}
d[4] = d.get(3, 8) # d.get(3, 8) returns 33 since 3 is in d
# d = {3: 33, 5: 12, 4: 33}
print(d) # Output: {3: 33, 5: 12, 4: 33}Click to reveal
7. Real-world uses
- Dictionaries – JSON-like configs, counting word frequencies, caching results.
- Sets – Removing duplicates from a list, membership testing (
if x in big_set), finding common tags between users.
8. Practice suggestions
- Word counter – ask the user for a sentence, build a
{word: count}dict. - Student registry – store students (ID → dict of info); add, update, delete.
- Duplicate remover – write a function that takes a list and returns a list of unique items (hint: convert to set, then back to list).
- Set algebra – given two lists of course codes, output courses common to both, only in set A, etc.
9. Key takeaways (quick memory jog)
- Dict ⟹ key → value mapping, keys unique & immutable,
.get()is your friend. - Nested dicts model "things inside things."
- Set ⟹ unique collection, supports union/intersection maths.
- Only immutable (hashable) objects can live inside a set or act as dict keys.