Skip to content

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. Use set() for an empty set).

Mathematical Operations:

OperationOperatorMethod EquivalentLogic
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, leaving set().
  • remove(elem) vs. discard(elem) (Critical Distinction):
  • remove(5): Deletes 5. Raises a KeyError if 5 does not exist.
  • discard(5): Deletes 5. Fails silently (does nothing) if 5 does not exist.

  • Core Logic: Unordered (historically) collections mapping unique Keys to Values.
  • Initialization: d = {'key': 'value', 1: 'one'}.

Key Constraints:

  1. Uniqueness: Keys must be unique. Reusing a key overwrites the previous value ({'a': 1, 'a': 2} resolves to {'a': 2}).
  2. Immutability: Keys must be strictly immutable/hashable types (strings, integers, tuples). Using a mutable type like a list as a key raises a TypeError.

Core Operations:

  • Access: d['key'] (Raises KeyError if 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. Returns default (or None) if the key is missing, bypassing KeyError.
  • pop(key, [default]): Removes the key and returns its value. Returns default if missing (or raises KeyError if 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 for for 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 specified value (default is None).
  • setdefault(key, [default]): Best practice for nested structures. Returns the value if key exists. If not, initializes key with default and returns default.
  • Example: d.setdefault("node", []).append("item") replaces if "node" not in d: d["node"] = [].