🐍 Python 2026 › Lesson 8: Dictionaries and Sets
Lesson 8 of 30

Dictionaries and Sets

Key-value pairs, set operations, and when to use each collection type.

Dictionaries

A dictionary stores data as key: value pairs. Keys must be unique and immutable (strings, numbers, tuples).

student = {
    "name": "Diana",
    "age": 21,
    "grade": "A"
}
print(student["name"])          # Diana
print(student.get("age"))       # 21
student["email"] = "[email protected]"  # add key
student["age"] = 22              # update value
del student["grade"]            # delete key

Iterating Over Dictionaries

for key, value in student.items():
    print(f"{key}: {value}")

print(list(student.keys()))    # all keys
print(list(student.values()))  # all values

Sets

A set is an unordered collection of unique elements. Useful for membership testing and eliminating duplicates:

colours = {"red", "green", "blue", "red"}
print(colours)   # {'red', 'green', 'blue'}  (no duplicate)

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)   # union:        {1,2,3,4,5,6}
print(a & b)   # intersection: {3,4}
print(a - b)   # difference:   {1,2}
✅ When to Use Each
Use a list when order matters. Use a dict for labelled data. Use a set for fast membership tests or removing duplicates.