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
🔑 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:
- Computes a hash: Converts the key into a number (hash value)
- Finds a location: Uses the hash to determine where to store the value in memory
- Stores the pair: Saves both the key and value at that location
- 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:
Method 2: Using dict() Constructor
⚠️ 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 []
Method 2: get() Method (Safer!)
💡 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
Removing Items
🛠️ Essential Dictionary Methods
Dictionaries come with powerful built-in methods. Let's explore them all!
Viewing Keys, Values, and Items
Checking Membership
Copying Dictionaries
Dictionary Comprehensions
🎯 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
🚫 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
Adding and Removing Items
Set Membership Testing
🔗 Set Operations - Mathematical Set Theory
Sets support mathematical operations like union, intersection, and difference. These are incredibly useful for comparing collections!
Union - Combine Sets
Intersection - Common Items
Difference - Items in First But Not Second
Symmetric Difference - Items in Either But Not Both
📊 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
📺 Video Resources
Watch these videos to reinforce your understanding of dictionaries and sets:
Python Dictionaries Explained
Clear explanation of dictionaries, key-value pairs, and when to use them.
Watch VideoPython Sets Tutorial
Comprehensive guide to sets and set operations with practical examples.
Watch VideoDictionary Methods in Python
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.
Part 2: Set Exercises
Exercise 2: Find Common Friends
Task: Use sets to find common friends between two people.
🎉 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!
What is a dictionary in Python?
Which is safer: dict["key"] or dict.get("key")?
What does {1, 2, 2, 3, 3, 3} create?
Which set operation finds items in both sets?
Can lists be used as dictionary keys?