Lecture 3: Sets and Dictionaries

1. Set Initialization

Sets are unordered collections of unique elements.

# Empty set (note: {} creates an empty dictionary) empty_set = set() # Set with elements numbers = {1, 2, 3, 4, 5} mixed = {1, "hello", 3.14, (1, 2, 3)} # Can contain tuples (immutable) # From a list (removes duplicates) colors = set(["red", "green", "blue", "red"]) # {'red', 'green', 'blue'} # Set comprehension squares = {x**2 for x in range(5)} # {0, 1, 4, 9, 16}

2. Set Methods

Method Description Example
add(x) Adds element x to the set s.add(4)
remove(x) Removes x; raises KeyError if not found s.remove(4)
discard(x) Removes x if present (no error if not found) s.discard(4)
pop() Removes and returns an arbitrary element elem = s.pop()
clear() Removes all elements s.clear()

3. Set Operations

Operation Description Example
Union (|) Elements in either set a | b or a.union(b)
Intersection (&) Elements in both sets a & b or a.intersection(b)
Difference (-) Elements in a but not in b a - b or a.difference(b)
Symmetric Difference (^) Elements in either set but not both a ^ b or a.symmetric_difference(b)
Subset (<=) Test if all elements of a are in b a <= b or a.issubset(b)
Superset (>=) Test if all elements of b are in a a >= b or a.issuperset(b)
a = {1, 2, 3} b = {3, 4, 5} # Union print(a | b) # {1, 2, 3, 4, 5} # Intersection print(a & b) # {3} # Difference print(a - b) # {1, 2} # Symmetric Difference print(a ^ b) # {1, 2, 4, 5}

4. Dictionary Initialization

Dictionaries store key-value pairs (mutable, ordered as of Python 3.7).

# Empty dictionary empty_dict = {} # Dictionary with key-value pairs student = { "name": "John", "age": 20, "courses": ["Math", "Computer Science"] } # Using dict() constructor another_dict = dict(name="Alice", age=22) # Dictionary comprehension squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

5. Dictionary Methods

Method Description Example
keys() Returns a view of all keys student.keys()
values() Returns a view of all values student.values()
items() Returns a view of key-value pairs student.items()
get(key, default) Returns value for key, or default if not found age = student.get('age', 0)
pop(key, default) Removes key and returns its value age = student.pop('age')
update(dict2) Updates dictionary with key-value pairs from dict2 student.update({'age': 21, 'grade': 'A'})
setdefault(key, default) Returns value if key exists, else inserts key with default value grade = student.setdefault('grade', 'B')

6. Nesting in Dictionaries

Dictionaries can contain other dictionaries, lists, and other data types.

# Nested dictionary students = { "student1": { "name": "John", "age": 20, "courses": ["Math", "Physics"] }, "student2": { "name": "Alice", "age": 22, "courses": ["Computer Science", "Math"], "grades": { "Math": "A", "Computer Science": "A+" } } } # Accessing nested elements alice_math_grade = students["student2"]["grades"]["Math"] # 'A' # Adding a new student students["student3"] = { "name": "Bob", "age": 21, "courses": ["Physics", "Chemistry"] } # Dictionary with list values courses = { "CS101": ["Introduction to CS", 3, 30], "MATH201": ["Linear Algebra", 4, 25] } # Dictionary with tuple keys coordinates = { (35.6895, 139.6917): "Tokyo", (40.7128, -74.0060): "New York" }