0% Complete

👋 Welcome Young Pythonista!

Let's explore the amazing world of Sets and Dictionaries!

0

Points

0

Badges

0

Exercises

{} set() dict {1,2,3}

Deep Dive into Python Sets

Beginner Friendly

🎯 What is a Set?

Python Snake

Hey there! Think of a Set like a magical bag that only keeps unique items! No duplicates allowed! 🎒✨

📚 Key Facts About Sets:

  • Sets store unique elements only - no duplicates!
  • Sets are unordered - items have no specific position
  • Sets are mutable - you can add or remove items
  • Sets use curly braces {} or the set() function
🐍 Python Code
# Creating a set
my_fruits = {"apple", "banana", "cherry"}
print(my_fruits)  # Output: {'apple', 'banana', 'cherry'}

# Sets remove duplicates automatically!
numbers = {1, 2, 2, 3, 3, 3}
print(numbers)  # Output: {1, 2, 3} - duplicates are gone!
💡

Fun Fact: Sets in Python work just like sets in math class! They're perfect for finding unique items in a collection.

🛠️ Creating Sets

Method 1: Using Curly Braces

# Direct creation
colors = {"red", "green", "blue"}

Method 2: Using set() Function

# From a list
my_list = [1, 2, 3, 3]
my_set = set(my_list)  # {1, 2, 3}

Method 3: Empty Set

# Must use set() for empty set
empty_set = set()
# NOT {} - that creates an empty dictionary!

⚠️ Common Mistake!

# This creates a DICTIONARY, not a set!
wrong = {}  # Empty dictionary
right = set()  # Empty set

⚡ Set Operations

Add Element

fruits = {"apple", "banana"}
fruits.add("cherry")
# {"apple", "banana", "cherry"}

Remove Element

fruits.remove("banana")
# {"apple", "cherry"}
# Or use discard() - no error if not found
fruits.discard("mango")

Union (All items)

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2  # or set1.union(set2)
# {1, 2, 3, 4, 5}

Intersection (Common items)

set1 = {1, 2, 3}
set2 = {3, 4, 5}
common = set1 & set2  # or set1.intersection(set2)
# {3}

Difference

set1 = {1, 2, 3}
set2 = {3, 4, 5}
diff = set1 - set2  # or set1.difference(set2)
# {1, 2}

🎨 Interactive Venn Diagram

Set A
1, 2, 3
Set B
3, 4, 5
3
Result: {1, 2, 3, 4, 5}

🧰 Useful Set Methods

Method Description Example
add() Adds an element s.add(4)
remove() Removes element (error if not found) s.remove(2)
discard() Removes element (no error if not found) s.discard(2)
pop() Removes and returns random element item = s.pop()
clear() Removes all elements s.clear()
len() Returns number of elements len(s)
in Check if element exists 3 in s

Practice Time: Sets Exercises

Exercise 1 Easy +15 points

Create a set called my_set containing the numbers 1, 2, 3, 4, 5. What do you write?

Exercise 2 Medium +20 points

What will be the output of this code?

numbers = {1, 2, 2, 3, 3, 3, 4}
print(len(numbers))
Exercise 3 Medium +20 points

Given set1 = {1, 2, 3} and set2 = {2, 3, 4}, what is the intersection?

Exercise 4 Challenge +30 points

Match the set operation with its result for sets A = {1, 2, 3} and B = {3, 4, 5}

A | B (Union)
A & B (Intersection)
A - B (Difference)
{3}
{1, 2}
{1, 2, 3, 4, 5}
Exercise 5 Challenge +25 points

Complete the code to find all unique characters in "hello world":

text = "hello world"
unique_chars = 
print(unique_chars)

Sets Mini Quiz

Test your knowledge! Complete this quiz to earn the Sets Master Badge! 🏆

Question 1 of 5

Deep Dive into Python Dictionaries

Intermediate Level

📖 What is a Dictionary?

Python Snake

Think of a Dictionary like a real dictionary! 📚 You look up a word (key) to find its meaning (value)!

📚 Key Facts About Dictionaries:

  • Dictionaries store key-value pairs
  • Keys must be unique and immutable (strings, numbers, tuples)
  • Values can be any data type
  • Use curly braces {} with key:value format
  • Dictionaries are ordered (Python 3.7+)

🎨 Visual Representation

"name"
"Alice"
"age"
12
"grade"
"7th"
🐍 Python Code
# Creating a dictionary
student = {
    "name": "Alice",
    "age": 12,
    "grade": "7th"
}

# Accessing values
print(student["name"])  # Output: Alice
print(student["age"])   # Output: 12
🌟

Did you know? Dictionaries in Python are incredibly fast at looking up values! They use something called "hash tables" behind the scenes.

🛠️ Creating Dictionaries

Method 1: Curly Braces

# Direct creation
person = {"name": "Bob", "age": 25}

Method 2: dict() Constructor

# Using dict()
person = dict(name="Bob", age=25)

Method 3: From Lists

# From two lists
keys = ["a", "b", "c"]
values = [1, 2, 3]
my_dict = dict(zip(keys, values))

Method 4: Empty Dictionary

# Empty dictionary
empty_dict = {}
# OR
empty_dict = dict()

🔑 Accessing and Modifying Values

Access Value

student = {"name": "Alice", "age": 12}

# Method 1: Square brackets
print(student["name"])  # Alice

# Method 2: get() - safer!
print(student.get("name"))  # Alice
print(student.get("grade", "N/A"))  # N/A (default)

Add/Update Value

student = {"name": "Alice"}

# Add new key-value pair
student["age"] = 12

# Update existing value
student["name"] = "Bob"

print(student)  # {'name': 'Bob', 'age': 12}

Delete Elements

student = {"name": "Alice", "age": 12, "grade": "A"}

# Using del
del student["grade"]

# Using pop() - returns the value
age = student.pop("age")  # age = 12

print(student)  # {'name': 'Alice'}

🎮 Try It Yourself: Build a Dictionary!

my_dict = {}

🧰 Dictionary Methods

Method Description Example
keys() Returns all keys d.keys()
values() Returns all values d.values()
items() Returns key-value pairs as tuples d.items()
get(key) Returns value (None if not found) d.get("name")
pop(key) Removes and returns value d.pop("age")
update() Updates with another dict d.update({"x": 1})
clear() Removes all items d.clear()
🐍 Looping Through Dictionaries
student = {"name": "Alice", "age": 12, "grade": "A"}

# Loop through keys
for key in student.keys():
    print(key)

# Loop through values
for value in student.values():
    print(value)

# Loop through both
for key, value in student.items():
    print(f"{key}: {value}")

🏠 Nested Dictionaries

Python Snake

Dictionaries can contain other dictionaries! It's like having folders inside folders! 📁📁

🐍 Nested Dictionary Example
# A classroom with students
classroom = {
    "student1": {
        "name": "Alice",
        "age": 12,
        "grades": {"math": 95, "science": 88}
    },
    "student2": {
        "name": "Bob",
        "age": 13,
        "grades": {"math": 82, "science": 90}
    }
}

# Accessing nested values
print(classroom["student1"]["name"])  # Alice
print(classroom["student1"]["grades"]["math"])  # 95

🎨 Visual: Nested Dictionary Structure

classroom
"student1"
"name": "Alice"
"age": 12
"grades"
"math": 95
"science": 88

Practice Time: Dictionary Exercises

Exercise 1 Easy +15 points

Create a dictionary called pet with keys "name" and "species", with values "Buddy" and "dog":

Exercise 2 Easy +15 points

What will this code print?

info = {"city": "Paris", "country": "France"}
print(info["city"])
Exercise 3 Medium +20 points

How do you safely get a value that might not exist?

data = {"x": 10}
# Get value for key "y" with default 0 if not found
Exercise 4 Medium +20 points

Arrange the code in correct order to create a dictionary and add a new key:

print(student)
student = {"name": "Alice"}
student["age"] = 12
Exercise 5 Challenge +30 points

Given this nested dictionary, what code accesses Bob's science grade?

school = {
    "class1": {
        "Alice": {"math": 95, "science": 88},
        "Bob": {"math": 82, "science": 90}
    }
}

Dictionaries Mini Quiz

Complete this quiz to earn the Dictionary Master Badge! 🏆

Question 1 of 5

My Badge Collection

🌟

Sets Explorer

Complete all Sets theory sections

Locked
💪

Sets Practitioner

Complete all Sets exercises

Locked
👑

Sets Master

Pass the Sets quiz with 80%+

Locked
📚

Dictionary Explorer

Complete all Dictionary theory sections

Locked
🔥

Dictionary Practitioner

Complete all Dictionary exercises

Locked
🏆

Dictionary Master

Pass the Dictionary quiz with 80%+

Locked
🐍

Python Champion

Earn all other badges!

Locked

Speed Learner

Score 100 points in under 10 minutes

Locked

Your Stats

0

Total Points

0

Badges Earned

0

Exercises Done

0:00

Time Learning