Chapter 5

Dictionaries & Sets

Master key-value pairs and unique collections - essential data structures for real-world programming!

📚 What are Dictionaries?

A dictionary stores data as key-value pairs. Think of it like a real dictionary - you look up a word (key) to find its definition (value), or like a phone book where you look up a name (key) to find a phone number (value)!

In Chapter 4, you learned about lists and tuples - ordered collections where you access items by their position (index 0, 1, 2...). Dictionaries are different: you access values using meaningful keys instead of numbers!

Quick Comparison: List vs Dictionary

Output will appear here...

🔑 Key-Value Pairs

Each item has a key and value

{"name": "Krishna"}

⚡ Fast Lookup

Find values instantly by key

dict["name"] → "Krishna"

✏️ Mutable

Can add, modify, delete items

dict["age"] = 26

🔤 Flexible Keys

Keys can be strings, numbers, tuples

{1: "one", "two": 2}

🔍 Behind the Scenes: How Dictionaries Work

Dictionaries use something called a hash table. When you store a value with a key, Python:

  1. Computes a hash: Converts the key into a number (hash value)
  2. Finds a location: Uses the hash to determine where to store the value in memory
  3. Stores the pair: Saves both the key and value at that location
  4. Lightning-fast retrieval: Uses the same hash to instantly find the value later!
When you do: student["name"]
1. Python hashes "name" → gets number (e.g., 12345)
2. Looks at memory location 12345
3. Finds "Krishna" instantly!

This is MUCH faster than searching through a list!

Time Complexity:

  • List lookup: O(n) - might check every item
  • Dictionary lookup: O(1) - goes directly to the value! ⚡

🛠️ Creating Dictionaries

There are several ways to create dictionaries in Python. Let's explore them all!

Method 1: Using Curly Braces {}

The most common way - use curly braces with key:value pairs separated by commas:

Output will appear here...

Method 2: Using dict() Constructor

Output will appear here...

⚠️ Important: What CAN and CANNOT Be Keys

Keys must be immutable (unchangeable) types:

# ✅ VALID KEYS (immutable)
valid_dict = {
    "string": "value",           # strings ✓
    42: "value",                 # numbers ✓
    (1, 2): "value",            # tuples ✓
    3.14: "value"               # floats ✓
}

# ❌ INVALID KEYS (mutable - will cause error!)
# bad_dict = {
#     [1, 2]: "value",     # lists ✗ (mutable)
#     {"a": 1}: "value"    # dicts ✗ (mutable)
# }

# Values can be ANYTHING (mutable or immutable)
flexible_values = {
    "list": [1, 2, 3],
    "dict": {"nested": "value"},
    "set": {1, 2, 3}
}

🔑 Accessing Dictionary Values

There are several ways to get values from a dictionary. Each has its use case!

Method 1: Square Brackets []

Output will appear here...

Method 2: get() Method (Safer!)

Output will appear here...

💡 When to Use [] vs get()

Use [] Use get()
You're SURE the key exists Key might not exist
You WANT an error if missing Want default value if missing
Required data Optional data

Adding and Modifying Values

Output will appear here...

Removing Items

Output will appear here...

🛠️ Essential Dictionary Methods

Dictionaries come with powerful built-in methods. Let's explore them all!

Viewing Keys, Values, and Items

Output will appear here...

Checking Membership

Output will appear here...

Copying Dictionaries

Output will appear here...

Dictionary Comprehensions

Output will appear here...

🎯 Sets - Collections of Unique Items

A set is an unordered collection of unique items. Think of it like a bag of marbles where you can't have two identical marbles - duplicates are automatically removed!

Sets Automatically Remove Duplicates

Output will appear here...

🚫 No Duplicates

Each item appears only once

{1, 2, 3}

🔀 Unordered

No guaranteed order

No indexing like lists

⚡ Fast Membership

Quick to check if item exists

O(1) lookup time

✏️ Mutable

Can add/remove items

set.add(item)

Creating Sets

Output will appear here...

Adding and Removing Items

Output will appear here...

Set Membership Testing

Output will appear here...

🔗 Set Operations - Mathematical Set Theory

Sets support mathematical operations like union, intersection, and difference. These are incredibly useful for comparing collections!

Union - Combine Sets

Output will appear here...

Intersection - Common Items

Output will appear here...

Difference - Items in First But Not Second

Output will appear here...

Symmetric Difference - Items in Either But Not Both

Output will appear here...

📊 Visual Summary of Set Operations

Set A = {1, 2, 3, 4}
Set B = {3, 4, 5, 6}

UNION (A | B):              {1, 2, 3, 4, 5, 6}
  → Everything from both sets

INTERSECTION (A & B):       {3, 4}
  → Only items in both sets

DIFFERENCE (A - B):         {1, 2}
  → Items in A but not B

DIFFERENCE (B - A):         {5, 6}
  → Items in B but not A

SYMMETRIC DIFF (A ^ B):     {1, 2, 5, 6}
  → Items in either A or B but not both

Subset and Superset Operations

Output will appear here...

📺 Video Resources

Watch these videos to reinforce your understanding of dictionaries and sets:

Python Dictionaries Explained

Programming with Mosh

Clear explanation of dictionaries, key-value pairs, and when to use them.

Watch Video

Python Sets Tutorial

Corey Schafer

Comprehensive guide to sets and set operations with practical examples.

Watch Video

Dictionary Methods in Python

Tech With Tim

Deep dive into all the useful dictionary methods and when to use them.

Watch Video

🤖 AI Learning Prompts

Use these prompts with AI assistants to deepen your understanding:

Understanding Dictionaries

I'm learning about Python dictionaries. Please help me understand:

1. Explain how dictionaries work behind the scenes (hash tables)
2. When should I use dictionaries vs lists? Give me 5 specific scenarios
3. What's the difference between dict["key"] and dict.get("key")?
4. Show me 10 practical examples of using dictionaries
5. Explain dictionary methods: keys(), values(), items(), update()

Use simple language and real-world analogies!

Mastering Sets

Help me become an expert with Python sets:

1. What are sets and why do they only store unique items?
2. Explain all set operations: union, intersection, difference, symmetric difference
3. When should I use sets instead of lists?
4. Show me practical examples where sets make code cleaner and faster
5. Give me 5 exercises to practice set operations

Include step-by-step examples!

Practical Applications

Show me how to use dictionaries and sets in real projects:

1. How do I store and manage student records using dictionaries?
2. Show me how to use sets to remove duplicates from data
3. Create a contact management system using dictionaries
4. How can I use set operations to compare two lists?
5. Give me a mini-project that combines dictionaries and sets

Make it beginner-friendly with complete code!

💡 Tips for Using These Prompts:

  • Start simple: Master one concept before moving to the next
  • Practice daily: Ask for new examples and exercises regularly
  • Build projects: Request small projects that use these data structures
  • Compare approaches: Understanding when to use each structure is key

✏️ Practice Exercises

How to Approach These Exercises:

  • Start simple: Begin with guided exercises to build confidence
  • Experiment: Try different approaches to solve each problem
  • Test thoroughly: Try edge cases and different inputs

Part 1: Dictionary Exercises

Exercise 1: Student Grade Manager

Task: Create a dictionary to store and manage student grades.

Output will appear here...

Part 2: Set Exercises

Exercise 2: Find Common Friends

Task: Use sets to find common friends between two people.

Output will appear here...

🎉 Congratulations!

You've completed Chapter 5! You now know:

  • How to create and use dictionaries with key-value pairs
  • Dictionary methods and operations
  • How to create and use sets for unique collections
  • Set operations (union, intersection, difference)
  • When to use dictionaries vs sets vs lists

Next Step: Move on to Chapter 6 to learn about string manipulation!

📝 Knowledge Check - Test Your Understanding!

Answer these questions to check your understanding of Chapter 5. Get instant feedback on each answer!

Question 1 of 5

What is a dictionary in Python?

Question 2 of 5

Which is safer: dict["key"] or dict.get("key")?

Question 3 of 5

What does {1, 2, 2, 3, 3, 3} create?

Question 4 of 5

Which set operation finds items in both sets?

Question 5 of 5

Can lists be used as dictionary keys?