Day 7: Dictionaries, Sets & Weekly Mini-Project

🐍 Day 7: Dictionaries, Sets & Weekly Mini-Project


1. Learning Objectives

By the end of Day 7, you will be able to:

  • Create and work with dictionaries — Python's key-value data structure

  • Perform CRUD operations (Create, Read, Update, Delete) on dictionaries

  • Create and work with sets — unique, unordered collections

  • Apply set operations: union, intersection, difference

  • Combine everything from Days 1–7 into a working mini-project

  • Think like a programmer: break down problems, structure code, handle edge cases


2. Concept Explanation

2.1 Why Dictionaries? — Real-World Data is Labeled

Lists are great for ordered items. But real data often comes in key-value pairs — names and phone numbers, product IDs and prices, words and definitions.

A dictionary maps unique keys to values. Think of it like a real dictionary: you look up a word (key) to find its definition (value).

# A dictionary: keys → values
student = {
   "name": "Alex",
   "age": 21,
   "major": "Computer Science",
   "is_enrolled": True
}

2.2 Creating and Accessing Dictionaries

# Empty dictionary
empty = {}

# With data
phone_book = {"Alice": "555-1234", "Bob": "555-5678"}

# Access values by key
print(phone_book["Alice"])       # 555-1234
# print(phone_book["Charlie"])   # KeyError: 'Charlie' — key doesn't exist

# Safe access with .get()
print(phone_book.get("Charlie"))        # None — no error
print(phone_book.get("Charlie", "N/A")) # N/A — custom default

2.3 Modifying Dictionaries

inventory = {"apples": 10, "bananas": 5}

# Add or update
inventory["oranges"] = 8       # Add new key-value pair
inventory["apples"] = 12       # Update existing value

# Remove
inventory.pop("bananas")       # Remove key and return value → 5
del inventory["oranges"]       # Remove key (no return)
inventory.clear()              # Remove all items

2.4 Dictionary Operations

student = {"name": "Maria", "age": 28, "city": "Manila"}

# Keys and values
print(student.keys())      # dict_keys(['name', 'age', 'city'])
print(student.values())    # dict_values(['Maria', 28, 'Manila'])
print(student.items())     # dict_items([('name', 'Maria'), ('age', 28), ('city', 'Manila')])

# Check if key exists
print("age" in student)    # True
print("grade" in student)  # False

# Loop through dictionary
for key in student:
   print(f"{key}: {student[key]}")

# Better: iterate over items directly
for key, value in student.items():
   print(f"{key}: {value}")

# Merge dictionaries
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
a.update(b)
print(a)  # {'x': 1, 'y': 3, 'z': 4} — duplicate keys get overwritten

💡 Dictionary keys must be immutable (strings, numbers, tuples — NOT lists). Values can be anything.


2.5 Sets — Unique, Unordered Collections

A set is an unordered bag of unique items. It's perfect for removing duplicates, membership testing, and mathematical operations.

# Creating sets
fruits = {"apple", "banana", "cherry"}
empty_set = set()          # {} creates a dictionary, not a set!
from_list = set([1, 2, 2, 3])  # {1, 2, 3} — duplicates removed automatically

# Adding and removing
fruits.add("orange")
fruits.remove("banana")    # KeyError if not present
fruits.discard("mango")    # No error if not present — safer
removed = fruits.pop()     # Remove and return an ARBITRARY element

2.6 Set Operations — Like Math Class

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)       # Union: {1, 2, 3, 4, 5, 6}
print(a & b)       # Intersection: {3, 4}
print(a - b)       # Difference: {1, 2} (in a but not b)
print(b - a)       # Difference: {5, 6} (in b but not a)
print(a ^ b)       # Symmetric difference: {1, 2, 5, 6} (in either, not both)

# With methods
print(a.union(b))
print(a.intersection(b))

Real-world uses:

# Find common elements
python_devs = {"Alice", "Bob", "Charlie"}
java_devs = {"Bob", "Charlie", "David"}
both = python_devs & java_devs
print(f"Knows both: {both}")  # {'Bob', 'Charlie'}

# Remove duplicates from a list
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers))
print(unique)  # [1, 2, 3, 4] — but order is not guaranteed!

2.7 Dictionary vs. List vs. Set — Decision Guide

Feature List Dict Set
Syntax [1, 2, 3] {"a": 1} {1, 2, 3}
Ordered? ✅ Yes (insertion) ✅ Yes (3.7+ by insertion) ❌ No
Mutable? ✅ Yes ✅ Yes ✅ Yes
Duplicates? ✅ Allowed Keys: ❌ / Values: ✅ ❌ Removed
Access by Index (0, 1, …) Key (string, etc.) Not directly (use in)
Best for Ordered sequences Lookup tables, mappings Uniqueness, math ops

2.8 Common Mistakes

Mistake Example Fix
Accessing missing key with [] d["nonexistent"]KeyError Use d.get("nonexistent")
Creating empty set with {} s = {} is a dict, not a set Use s = set()
Using mutable key in dict {[1, 2]: "value"}TypeError Use a tuple: {(1, 2): "value"}
Assuming set order {1, 2, 3} may print in any order Don't rely on set ordering
Modifying dict while looping for k in d: + del d[k] Loop over a copy: list(d.keys())

3. Code Examples

Example 1: Phone Book Application

contacts = {
   "Alice": "555-1234",
   "Bob": "555-5678",
   "Charlie": "555-9012"
}

# Lookup
name = input("Search for contact: ")
phone = contacts.get(name, "Not found")
print(f"{name}: {phone}")

# Add new
new_name = input("Add name: ")
new_phone = input("Add phone: ")
contacts[new_name] = new_phone

# List all
print("\n--- All Contacts ---")
for name, phone in contacts.items():
   print(f"{name}: {phone}")

Example 2: Unique Word Counter

sentence = "the cat chased the rat and the rat chased the cat"
words = sentence.split()
unique_words = set(words)
print(f"Total words: {len(words)}")
print(f"Unique words: {len(unique_words)}")
print(f"Unique words: {unique_words}")

Example 3: Student Grade Tracker

grades = {"Alice": 85, "Bob": 92, "Charlie": 78}

# Add/update
grades["David"] = 90

# Average
average = sum(grades.values()) / len(grades)
print(f"Average: {average:.1f}")

# Find highest and lowest
highest = max(grades, key=grades.get) # Returns the KEY, not value
lowest = min(grades, key=grades.get)
print(f"Top student: {highest} ({grades[highest]})")
print(f"Lowest: {lowest} ({grades[lowest]})")

4. Hands-On Exercises

Exercise 1: Dictionary Basics

Create a dictionary called person with keys: name, age, city. Print each value. Then add a new key job and update age to a new value.

Exercise 2: Word Frequency Counter

Ask the user for a sentence. Split it into words. Count how many times each word appears using a dictionary. Print the result.

Exercise 3: Set Operations

Create two sets: evens = {2, 4, 6, 8, 10} and multiples_of_5 = {5, 10, 15, 20}. Find and print their union, intersection, and difference (evens minus multiples_of_5).

Exercise 4: Duplicate Remover

Given nums = [1, 2, 2, 3, 3, 3, 4, 5, 5], use a set to create a list with no duplicates. Print both the original and deduplicated lists.

Exercise 5: Dictionary Search

Create a dictionary of 5 countries and their capitals. Ask the user for a country name and print its capital. If the country isn't in the dictionary, print "Capital not found."


5. Applied Challenge Task 🏗️

Weekly Mini-Project: Multi-Feature Console Utility App

This is your first capstone milestone — a program that combines everything from Days 1–7. Build it step by step.

Core Requirements

Your app should have a main menu that offers these features:

=== UTILITY HUB ===
[1] Calculator
[2] Grade Tracker
[3] Contact Manager
[4] Quiz Game
[5] Quit

Feature 1: Calculator

  • Ask for two numbers and an operator (+, -, *, /)

  • Perform the operation and show the result

  • Handle division by zero gracefully

  • Loop until the user chooses to return to the main menu

Feature 2: Grade Tracker

  • Start with an empty dictionary: student names as keys, a list of their scores as values

  • Allow the user to: add a student, add a score to a student, view all grades, view a student's average

  • Show letter grade alongside average

  • Use functions for calculating average and letter grade

Feature 3: Contact Manager

  • Store contacts in a dictionary: name → phone number

  • Support: add, search, delete, list all

  • Search should work with partial names (use in)

Feature 4: Quiz Game

  • Store at least 5 questions and answers in a list of dictionaries: [{"question": "...", "answer": "..."}, ...]

  • Loop through each question, ask the user, track their score

  • At the end, show "You scored X out of Y"

  • Handle case-insensitive answers (.lower())

Example Structure

utility_hub.py
├── main() # Main menu loop
├── calculator_mode() # Feature 1
├── grade_tracker() # Feature 2
├── contact_manager() # Feature 3
└── quiz_game() # Feature 4

Stretch Goals

  • Save contacts to a file and load them on startup (preview of Day 9!)

  • Add input validation throughout (no crashes on bad input)

  • Track and display the time taken for the quiz (use time module)

  • Let the quiz game have multiple-choice answers


6. Brief Review Summary

Concept Key Points
Dictionary {key: value} — mutable, key-value pairs; keys must be immutable
Access dict[key] or dict.get(key, default)
Common methods .keys(), .values(), .items(), .update(), .pop()
Set {1, 2, 3} — unordered, unique elements; mutable
Set operations \| (union), & (intersection), - (difference), ^ (sym. diff)
Empty set set(), NOT {} (which is an empty dict)
Membership in works on both dicts (checks keys) and sets

7. Phase 1 Complete! 🎉

You have now learned:

Day Topic
1 Variables, Data Types
2 Operators, I/O, Type Casting
3 Conditionals, Boolean Logic
4 Loops
5 Functions
6 Lists & Tuples
7 Dictionaries & Sets

Next stop: Phase 2 — Intermediate Programming (Days 8–15)

Day 8 kicks off with String Manipulation & Formatting — going deep on one of the most practical skills in Python.


🎯 Your Action Items for Day 7:

  1. ✅ Complete all 5 exercises

  2. ✅ Complete the Multi-Feature Console Utility App mini-project

  3. ✅ Experiment with nested dictionaries and sets of tuples

  4. ✅ Review all Phase 1 topics — you now have a solid foundation!


Comments

Popular posts from this blog

Day 1: Welcome to Python — Your Journey Begins

Python: Your Gateway to Coding Adventures

Day 11: List Comprehensions & Lambda Functions

Earn From the Comfort of Your Home

Build the skills to work comfortably from home, on your own terms.

Get Started Today