Lesson 9: Sets & Dictionaries
Unordered sets for lightning-fast membership, and key-value dictionaries for real-world data.
Dictionaries — Data with Names
A dictionary stores key-value pairs — like a real dictionary where you look up a word (the key) and read its meaning (the value). Keys must be unique and immutable (strings, numbers, tuples). Values can be anything.
student = {"name": "Riya", "course": "Python", "score": 92}
Dictionaries are the most important data structure in Python after lists. Almost every API response, database row, and configuration file ends up as a dict. Master dicts and you can model almost any real-world record.
What You'll Learn in This Lesson
- Create, read, update, and delete dictionary entries
- Use
.get()for safe access and.items()for iteration - Understand sets and their lightning-fast membership checks
- Apply set math: union, intersection, difference
Dictionary Essentials
| Operation | Syntax | Notes |
|---|---|---|
| Create | d = {"k": "v"} or d = dict(k="v") |
— |
| Read | d["k"] |
Raises KeyError if missing |
| Safe read | d.get("k", default) |
Returns default if missing |
| Add / update | d["k"] = "v2" |
Creates or overwrites |
| Delete | del d["k"] |
Raises KeyError if missing |
| Pop | d.pop("k", default) |
Removes and returns |
| All keys | d.keys() |
View of keys |
| All values | d.values() |
View of values |
| All pairs | d.items() |
View of (key, value) tuples |
The golden rule: use .get() for optional keys — never let a missing key crash your program.
student = {"name": "Riya", "score": 92}
print(student.get("grade", "Not assigned")) # Not assigned
student["grade"] = "A" # add a new key
for key, value in student.items():
print(f" {key}: {value}")
Mental model: a dictionary is a two-column table (key | value) with instant lookup. Python does not scan the table — it computes a hash of the key and jumps straight to the right row.
Checking for Keys — in vs get
| Approach | Behavior |
|---|---|
"k" in d |
Returns True/False — no error, no default needed |
d.get("k") |
Returns None if missing |
d.get("k", default) |
Returns default if missing |
d["k"] |
Raises KeyError if missing |
Use in when you need a yes/no answer; use .get() when you need a value with a fallback; use d["k"] only when you are certain the key exists.
Sets — Unique & Fast
A set is an unordered collection of unique items. Two superpowers:
- Deduplication: converting a list to a set removes duplicates in one line.
- Speed: membership checks (
x in set) are O(1) — instant, even with a million items.
colors = {"red", "green", "blue"}
colors.add("yellow")
colors.remove("red") # raises KeyError if missing
colors.discard("purple") # safe — no error if missing
Note: sets are unordered — you cannot index them (s[0] fails). And they can only hold hashable items, so lists and dicts cannot be set members.
Why O(1)? Like dict keys, set items are hashed — Python computes a number from the item and jumps directly to its storage slot. Compare that with a list, where x in list may scan every element (O(n)). For a million items, that is a million comparisons versus one hash computation.
Set Operations — Math for Data
| Operation | Symbol | Method | Meaning |
|---|---|---|---|
| Union | `A | B` | A.union(B) |
| Intersection | A & B |
A.intersection(B) |
Items in both |
| Difference | A - B |
A.difference(B) |
In A, not in B |
| Symmetric diff | A ^ B |
A.symmetric_difference(B) |
In exactly one |
batch1 = {"Amol", "Riya", "Sam"}
batch2 = {"Riya", "Sam", "Neha"}
print(batch1 | batch2) # {'Amol', 'Riya', 'Sam', 'Neha'}
print(batch1 & batch2) # {'Riya', 'Sam'}
print(batch1 - batch2) # {'Amol'}
Venn diagram: picture two overlapping circles. Union = everything, intersection = the overlap, difference = one circle minus the overlap.
When to Use What
| Need | Use | Why |
|---|---|---|
| Ordered, changeable items | List | Workhorse collection |
| Fixed record | Tuple | Immutable, fast |
| Lookup by name | Dict | Key → value, O(1) |
| Membership / dedupe | Set | O(1) in checks |
Real-world combos:
- Count unique visitors:
len(set(user_ids)). - Common friends on social media:
set(friends_a) & set(friends_b). - Words not in the dictionary:
set(words) - set(dictionary). - Group by category: a dict of lists, keyed by category (Lesson 10's
defaultdictmakes this elegant).
Common Mistakes to Avoid
- Mistake:
d["missing"]crashing — Fix: use.get("missing", default). - Mistake: Trying to use a list as a dict key or set member — Fix: convert to a tuple first.
- Mistake: Mutating a dict/set while iterating over it — Fix: iterate over a copy:
for k in list(d):. - Mistake: Expecting sets to keep insertion order — Fix: sets are unordered; use a list or dict if order matters.
- Mistake:
remove()crashing on a missing element — Fix: use.discard()when absence is acceptable.
Professional Tips & Tricks
- Always use
.get()for optional keys — never let a missing key crash your program. - Use
collections.Counterfor counting — it is a dict subclass made for tallying. - Convert a list to a set to remove duplicates in one line:
list(set(items)). - Use
inon sets for membership — O(1) versus O(n) for lists on large data. - Merge two dicts cleanly with
{**a, **b}ora | b(Python 3.9+).
Key Takeaways
- Dicts map unique immutable keys to values with O(1) lookup.
.get()prevents KeyErrors;.items()powers clean iteration.- Sets store unique items and give instant membership checks.
|,&,-,^perform set math.- Use
list(set(items))to deduplicate in one line. - Use
infor membership and.get()for safe value access.
Next up: The collections module — Counter, defaultdict, deque & namedtuple.
# Dictionaries: key-value data
student = {"name": "Riya", "course": "Python", "score": 92}
# Reading with .get() — safe access
print("Name:", student["name"])
print("Grade:", student.get("grade", "Not assigned"))
# Adding / updating
student["grade"] = "A"
print("Updated:", student)
# Iterating items
for key, value in student.items():
print(f" {key}: {value}")
# Sets: uniqueness + set math
batch1 = {"Amol", "Riya", "Sam"}
batch2 = {"Riya", "Sam", "Neha"}
print("Unique students:", batch1 | batch2)
print("In both batches:", batch1 & batch2)
print("Only in batch1:", batch1 - batch2)Lesson Code (Python)
# Dictionaries: key-value data
student = {"name": "Riya", "course": "Python", "score": 92}
# Reading with .get() — safe access
print("Name:", student["name"])
print("Grade:", student.get("grade", "Not assigned"))
# Adding / updating
student["grade"] = "A"
print("Updated:", student)
# Iterating items
for key, value in student.items():
print(f" {key}: {value}")
# Sets: uniqueness + set math
batch1 = {"Amol", "Riya", "Sam"}
batch2 = {"Riya", "Sam", "Neha"}
print("Unique students:", batch1 | batch2)
print("In both batches:", batch1 & batch2)
print("Only in batch1:", batch1 - batch2)Console Output
Name: Riya
Grade: Not assigned
Updated: {'name': 'Riya', 'course': 'Python', 'score': 92, 'grade': 'A'}
name: Riya
course: Python
score: 92
grade: A
Unique students: {'Amol', 'Riya', 'Sam', 'Neha'}
In both batches: {'Riya', 'Sam'}
Only in batch1: {'Amol'}Code Visualization Tips
- Draw a dict as a two-column table: key | value. Lookups jump straight to the right row.
- Visualize set operations as overlapping circles (Venn diagrams) — union, intersection, difference.
- Use 'x in container' as a mental instant-lookup for sets vs a linear scan for lists.
Professional Tips & Tricks
- Always use .get() for optional keys — never let a missing key crash your program.
- Use collections.Counter for counting — it is a dict subclass made for tallying.
- Convert a list to a set to remove duplicates in one line: list(set(items)).
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Problem 1: Word Frequency Counter 1
Test Your Knowledge
Instant feedbackQuick Check: Lesson 9: Sets, Dictionaries, Hash Maps & Lookup Performance
Up next · Continue learning
Advanced Collections — Counter, defaultdict & deque
Supercharge your data with Counter, defaultdict, deque, and namedtuple from the collections module.