Set & Dict
- Core Logic: Unordered collections of unique, hashable objects.
- Primary Uses: De-duplication, membership testing, and mathematical set theory operations.
- Initialization:
x = {1, 2, 3}. (Note:{}creates an empty dictionary, not an empty set. Useset()for an empty set).
Mathematical Operations:
| Operation | Operator | Method Equivalent | Logic |
|---|---|---|---|
| Intersection | & | .intersection(y) | Elements present in both x and y. |
| Union | | | .union(y) | All unique elements from both x and y. |
| Difference | - | .difference(y) | Elements in x that are not in y. |
| Sym. Difference | ^ | .symmetric_difference(y) | Elements in either x or y, but not both. |
Set Methods:
add(elem): Inserts a single element. (e.g.,x.add(4)).pop(): Removes and returns a random element.clear(): Empties the set, leavingset().remove(elem)vs.discard(elem)(Critical Distinction):remove(5): Deletes5. Raises aKeyErrorif5does not exist.discard(5): Deletes5. Fails silently (does nothing) if5does not exist.
Dictionaries (Associative Arrays)
Section titled “Dictionaries (Associative Arrays)”- Core Logic: Unordered (historically) collections mapping unique Keys to Values.
- Initialization:
d = {'key': 'value', 1: 'one'}.
Key Constraints:
- Uniqueness: Keys must be unique. Reusing a key overwrites the previous value (
{'a': 1, 'a': 2}resolves to{'a': 2}). - Immutability: Keys must be strictly immutable/hashable types (strings, integers, tuples). Using a mutable type like a
listas a key raises aTypeError.
Core Operations:
- Access:
d['key'](RaisesKeyErrorif missing). - Add/Update:
d['new_key'] = 10(Adds if missing, updates if existing). - Delete Item:
del d['key']. - Delete Dict:
del d(Removes object from memory entirely).
Dictionary Methods:
- Retrieval & Removal:
get(key, [default]): Safely retrieves a value. Returnsdefault(orNone) if the key is missing, bypassingKeyError.pop(key, [default]): Removes the key and returns its value. Returnsdefaultif missing (or raisesKeyErrorif no default is set).popitem(): Removes and returns a(key, value)tuple in LIFO (Last-In, First-Out) order.- Iteration:
keys(): Iterates keys (for k in d:is shorthand forfor k in d.keys():).values(): Iterates values.items(): Iterates(key, value)tuples simultaneously (for k, v in d.items():).- Modification:
update(other_dict): Merges another dictionary into the current one, overwriting matching keys and appending new ones.clear(): Removes all items, leaving{}.- Creation & Defaults:
copy(): Returns a shallow copy.fromkeys(iterable, [value]): Generates a new dictionary using elements from the iterable as keys, all set to the specifiedvalue(default isNone).setdefault(key, [default]): Best practice for nested structures. Returns the value ifkeyexists. If not, initializeskeywithdefaultand returnsdefault.- Example:
d.setdefault("node", []).append("item")replacesif "node" not in d: d["node"] = [].