Dictionaries & Sets (Hash Maps & Unique Collections)
12 Lessons • Hands-on practice
Copying Lists: The Reference Trap
Typing `b = a` doesn't copy the list. It creates a second alias pointing to the identical memory address. Use `a.copy()` or `a[:]` for a real duplicate.
Tuples: Immutable Sequences
Tuples are immutable lists defined with parentheses `()`. Once created, you cannot add, remove, or modify items.
Single-Item Tuples: The Comma Rule
Parentheses around a single value mean math grouping. To create a 1-item tuple, you MUST include a trailing comma `(item,)`.
Tuple Unpacking & Variable Swapping
Assign multiple variables at once by unpacking a tuple: `x, y = 10, 20`. Swap variables instantly with `a, b = b, a`.
Star Unpacking: `first, *rest = items`
Slap an asterisk `*` in front of a variable during unpacking to gather all remaining elements into a clean list.
What is a Dictionary: Key-Value Magic
Dictionaries store data in `key: value` pairs using curly braces `{}`. Lookups by key are lightning fast ($O(1)$ hash maps).
Accessing Keys & the Fatal `KeyError`
Asking for a key that does not exist in a dictionary immediately detonates your program with a fatal `KeyError`.
Safe Access with `.get()`
`.get(key, default)` safely returns a value. If the key is missing, it hands you `None` (or your custom fallback) without crashing.
Adding & Updating Keys
Assign to a key with `d[key] = val`. If the key exists, it overwrites the old value. If it's new, it creates it.
Deleting Keys: `.pop()` & `del`
`del d[key]` permanently removes a key. `d.pop(key)` removes the key and hands you the value that was stored there.
Iterating Dictionaries: `.items()` Supremacy
Loop through dictionaries using `.items()` to get both the key and the value unpacked simultaneously in each iteration.
Dictionary Merging: Pipe `|` Operator
Python 3.9+ merges dictionaries cleanly using the pipe operator `|`. Keys on the right side overwrite matching keys on the left.