ALL MODULESmodule_05.py

Dictionaries & Sets

~60 minTheoryLive CodingChallengeQuiz
theory.md

5. Dictionaries & Sets

5.1Key-Value Pairs (Dictionaries)

Think of a real-world dictionary — you look up a word (the key) to find its definition (the value). Or think of a phone contact list!

SHOW:

PYTHON
WHAT HAPPENED HERE
We created a dictionary using curly braces {} with key: value pairs. We retrieved values using key names inside square brackets: user["name"].
THE TECHNICAL NAME
A collection of labeled pairs is a dictionary. Each entry links a key to a value.
TAKEAWAY
Store labeled pairs using curly braces {"key": "value"}.

5.2Safely Reading & Updating Dictionaries

If you look up a missing key with dict["missing"], Python raises an error. But there's a safer way!

SHOW:

PYTHON
WHAT HAPPENED HERE
.get("email", default) safely returned "Not provided" instead of crashing. Then profile["status"] = "Active" added a new key-value pair.
THE TECHNICAL NAME
Using .get() prevents KeyError crashes. Dictionaries are mutable (can be updated anytime).
TAKEAWAY
Use .get() for safe lookups and dict[key] = value to update.

5.3Unique Collections (Sets)

Think of a bag of lottery balls — every ball has a distinct number, and duplicates are impossible.

SHOW:

PYTHON
WHAT HAPPENED HERE
Even though "python" was listed twice, the set automatically threw away the duplicate!
THE TECHNICAL NAME
An unordered collection of unique items is a set.
TAKEAWAY
Sets {"a", "b"} automatically remove duplicate items.

5.4Set Operations (Union & Intersection)

Think of comparing two friend lists to find mutual friends (overlap) or combining all friends into one party invite list.

SHOW:

PYTHON
WHAT HAPPENED HERE
The & operator found common items (intersection). The | operator combined all unique items (union).
THE TECHNICAL NAME
Matching overlap is intersection (&), and combining sets is union (|).
TAKEAWAY
Use & to find shared items and | to combine sets.
GOTCHA 1

KeyError when accessing a non-existent dictionary key directly with dict[key] instead of dict.get(key).

GOTCHA 2

Expecting set elements to maintain insertion order (sets are unordered).

GOTCHA 3

Using a mutable list as a dictionary key (keys must be immutable).

WHERE THIS SHOWS UP IN REAL CODE

Web APIs return JSON data formatted as dictionaries, while unique user IDs and tag filters use sets.

TRY THIS YOURSELF

Create a dict student = {'name': 'Sam', 'grade': 'A'}, add 'age': 20, and print student.keys().

live_coding — User Profile & Tag Aggregator

Observe how get() returns default value without crashing.

Python not loaded yet.
demo — Demonstrate dictionary key-value access, safe get(), set uniqueness, and set operations.

Demonstrate dictionary key-value access, safe get(), set uniqueness, and set operations.

challenge_1

Warm-up 1: Create a dictionary for a product and print its price.

Steps:

  1. Define product = {"item": "Laptop", "price": 999}.
  2. Print Price: $999.
Python not loaded yet.
challenge_2

Warm-up 2: Remove duplicates using a set.

Steps:

  1. Given raw_ids = [101, 102, 101, 103, 102].
  2. Convert to set to remove duplicates.
  3. Print unique count: Unique IDs: 3.
Python not loaded yet.
challenge_3

Warm-up 3: Safe dictionary lookup using .get().

Steps:

  1. Given config = {"theme": "dark"}.
  2. Fetch "fontSize" with default 14.
  3. Print Font Size: 14.
Python not loaded yet.
challenge_4

Apply-it 1: Update and add dictionary keys.

Steps:

  1. Given car = {"brand": "Tesla", "year": 2022}.
  2. Update year to 2024.
  3. Add color as "Red".
  4. Print Updated Car: {'brand': 'Tesla', 'year': 2024, 'color': 'Red'}.
Python not loaded yet.
challenge_5

Apply-it 2: Find common items in two sets.

Steps:

  1. Given club_a = {"Alice", "Bob", "Charlie"} and club_b = {"Bob", "David", "Alice"}.
  2. Find intersection of members in both clubs.
  3. Check if "Alice" is in both. Print Both in clubs: True.
Python not loaded yet.
challenge_6

Apply-it 3: Iterate over dictionary keys and values.

Steps:

  1. Given scores = {"Math": 90, "Science": 85}.
  2. Print total score: Total Score: 175.
Python not loaded yet.
challenge_7

Stretch Challenge: Word frequency counter.

Steps:

  1. Given list words = ["apple", "banana", "apple", "cherry", "banana", "apple"].
  2. Count frequency into a dictionary.
  3. Print Apple count: 3.
Python not loaded yet.
quiz — 9 questions
30s question timers are paused. Start individually or all together.
# question 1

What syntax creates a Python dictionary?

# question 2

What happens when accessing a non-existent key with `dict['missing']`?

# question 3

Why is `dict.get('key', default)` safer than `dict['key']`?

# question 4

What is a main characteristic of a Python set?

# question 5

Which set operator calculates the intersection (common items) of two sets?

# question 6

What does `user.keys()` return?

# question 7

Can a mutable list be used as a dictionary key?

# question 8

What is the result of `set([1, 1, 2, 3, 3])`?

# question 9

Which method returns key-value tuples from a dictionary?

discussion

# comments · dicts-sets

  • @priya · 2h ago

    The typewriter hero is such a nice touch.

    • @alex · 1h ago

      Totally agree! Made it super engaging.

  • @sam · 1d ago

    Finally a course where I can run code without leaving the page.