Python - Dicts & Sets

Overview

Estimated time: 30–40 minutes

Use dictionaries and sets effectively for fast lookups and membership tests. Learn hashing constraints and common operations.

Learning Objectives

  • Create and update dicts; understand key requirements and ordering.
  • Use sets for deduplication and membership tests.
  • Apply common dict/set operations idiomatically.

Prerequisites

Dictionaries

ages = {"Ann": 30, "Ben": 25}
ages["Cat"] = 28
print(ages.get("Ann"))
print(list(ages.keys()))

Expected Output: 30\n['Ann', 'Ben', 'Cat'] (order may reflect insertion)

Sets

items = {1, 2, 3}
items.add(2)
print(items)
print({1,2,3} | {3,4})  # union
print({1,2,3} & {2,3,4}) # intersection

Expected Output (example): {1, 2, 3}\n{1, 2, 3, 4}\n{2, 3}

Common Pitfalls

  • Using unhashable types (e.g., lists, dicts) as dict keys or set elements.
  • Assuming random ordering (insertion order is preserved in modern Python, but don't rely on it for semantics).

Checks for Understanding

  1. What types can be used as dict keys?
  2. How do you compute the intersection of two sets?
Show answers
  1. Hashable (immutable) types like str, int, tuple (containing hashables).
  2. s1 & s2

Exercises

  1. Count word frequencies in a short string using a dict.
  2. Given two lists, print the unique common elements using sets.