Week 4: Dictionaries, Sets & File I/O
Store key-value pairs, work with unique collections, read and write files β plus remote collaboration on GitHub.
π Overview: Days 1β4 cover dictionaries, sets, and file I/O. Day 5 is a mini-project combining all concepts. Day 6 reinforces GitHub remote collaborationβpull, push, fetch, merge, and resolving conflicts.
π Prerequisite: Week 1 (variables, conditionals, git basics), Week 2 (loops, git branching), Week 3 (lists, tuples, git push/pull).
π― Goal: By the end of this week, you'll confidently use dictionaries for fast lookups, sets for unique data, files for persistent storage, and collaborate effectively on GitHub.
Dictionaries
Sets
File I/O
More File I/O
Mini Project
GitHub Collab
Day 1 Dictionaries: Key-Value Stores
Learning Objectives: Create dictionaries, access values via keys, add/update entries, use dictionary methods (keys(), values(), items()), and handle missing keys safely with get().
Creating & Accessing
# Empty dictionary
empty = {}
# Pre-filled dictionary
student = {"name": "Amit", "age": 14, "grade": "A"}
# Access by key
print(student["name"]) # Amit
# Using get() to avoid KeyError
print(student.get("marks", 0)) # 0 (default)
Adding, Updating, Deleting
student["city"] = "Delhi" # add
student["age"] = 15 # update
del student["grade"] # delete
print(student) # {'name':'Amit','age':15,'city':'Delhi'}
Looping & Methods
for key in student:
print(key, student[key])
for value in student.values():
print(value)
for key, value in student.items():
print(f"{key}: {value}")
π§βπ» Exercise: Student Dictionary
Create a dictionary with your name, age, and favourite subject. Print all keys and values using items().
me = {"name": "Riya", "age": 13, "subject": "Math"}
for k, v in me.items():
print(f"{k}: {v}")
Day 2 Sets: Unique Collections
Learning Objectives: Understand that sets store unique, unordered items. Perform union, intersection, difference. Use set methods like add(), remove(), discard().
A | BAll unique items
A & BCommon items
A - BIn A not in B
Set Basics
empty_set = set() # NOT {} (that's dict)
nums = {1, 2, 3, 2, 1}
print(nums) # {1, 2, 3} duplicates removed
nums.add(4)
nums.discard(2) # no error if missing
Set Operations
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b) # Union: {1, 2, 3, 4}
print(a & b) # Intersection: {2, 3}
print(a - b) # Difference: {1}
print(b - a) # {4}
π§βπ» Exercise: Unique Words
Ask user for a sentence, split into words, create a set to find unique words.
sentence = input("Enter a sentence: ")
words = sentence.split()
unique = set(words)
print(f"Unique words ({len(unique)}): {unique}")
Day 3 File I/O: Read & Write
Learning Objectives: Open files in different modes ('r', 'w', 'a'). Read entire file content, read lines, write strings. Always close files.
read
write (overwrites)
append
read+write
Writing to a File
f = open("data.txt", "w")
f.write("Hello, Python!\n")
f.write("Week 4 is fun.")
f.close()
Reading from a File
f = open("data.txt", "r")
content = f.read() # whole string
print(content)
f.seek(0) # reset cursor
lines = f.readlines() # list of strings
f.close()
Appending to a File
with open("data.txt", "a") as f:
f.write("\nNew line added!")
π§βπ» Exercise: Log Writer
Write a program that asks for user input and appends it to a file called "log.txt" with a timestamp.
from datetime import datetime
entry = input("Log entry: ")
with open("log.txt", "a") as f:
f.write(f"{datetime.now()}: {entry}\n")
print("Logged!")
with statement β it automatically closes the file even if an error occurs.Day 4 More File I/O & Exceptions
Learning Objectives: Handle fileβrelated errors with try/except. Work with CSVβlike data. Use with efficiently. Loop over file lines without loading everything into memory.
Reading Line by Line (Memory Efficient)
with open("bigfile.txt", "r") as f:
for line in f:
print(line.strip())
Writing a CSV (Comma-Separated)
students = [("Amit",14,"A"), ("Sara",15,"B")]
with open("students.csv", "w") as f:
for name, age, grade in students:
f.write(f"{name},{age},{grade}\n")
Handling File Errors
try:
with open("missing.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found! Creating a new one.")
with open("missing.txt", "w") as f:
f.write("Start")
π§βπ» Exercise: Grade Reader
Read students.csv and print a dictionary mapping name β grade.
grades = {}
with open("students.csv", "r") as f:
for line in f:
name, age, grade = line.strip().split(',')
grades[name] = grade
print(grades)
with to avoid resource leaks.Day 5 Mini-Project: Phonebook Manager
Learning Objectives: Build a CRUD phonebook using dictionaries and file storage. Save contacts to a text file, load them on startup. Use sets to find duplicate names.
Project Structure
- Load existing contacts from
phonebook.txt(name,phone per line). - Provide menu: 1. Add, 2. Search, 3. Delete, 4. View all, 5. Save & Exit.
- Use a dictionary: name β phone number.
- Use set operations to detect duplicate names before adding.
import os
contacts = {}
filename = "phonebook.txt"
# Load existing
if os.path.exists(filename):
with open(filename, "r") as f:
for line in f:
name, phone = line.strip().split(',')
contacts[name] = phone
while True:
print("\n--- Phonebook ---")
print("1.Add 2.Search 3.Delete 4.View 5.Save & Exit")
choice = input("Choice: ")
if choice == '1':
name = input("Name: ")
if name in contacts:
print("Contact exists. Use a different name.")
continue
phone = input("Phone: ")
contacts[name] = phone
print("Added.")
elif choice == '2':
name = input("Name to search: ")
print(contacts.get(name, "Not found"))
elif choice == '3':
name = input("Name to delete: ")
if contacts.pop(name, None):
print("Deleted.")
else:
print("Not found.")
elif choice == '4':
for n, p in contacts.items():
print(f"{n}: {p}")
elif choice == '5':
with open(filename, "w") as f:
for n, p in contacts.items():
f.write(f"{n},{p}\n")
print("Saved. Goodbye!")
break
Day 6 GitHub Collaboration: Fetch, Merge & Conflicts
Learning Objectives: Understand remote tracking branches. Use git fetch and git pull. Merge branches and resolve simple conflicts. Simulate a collaborative workflow.
feature branch
fetch = download updates without merging | pull = fetch + merge
Important Commands
| Command | Purpose |
|---|---|
git fetch origin | Download remote changes, don't integrate |
git merge origin/main | Merge fetched changes into current branch |
git pull origin main | Fetch + merge in one step |
git push origin feature | Upload branch to remote |
Resolving a Simple Conflict
Conflict occurs when two branches change the same line. Git marks the file like:
<<<<<<< HEAD
print("Hello from main")
=======
print("Hello from feature")
>>>>>>> feature
Edit file to keep the correct version, remove the markers, then git add and git commit.
Collaboration Flow (Student Practice)
# Partner A pushes
git push origin main
# Partner B gets updates
git fetch origin
git merge origin/main
# If conflict β resolve β add β commit
git push origin main
git pull before starting new work. Use feature branches and pull requests (GitHub UI) for team projects.Week 4 Practice Problems
π° Beginner Level
1. Word Frequency (Dictionary)
text = "apple banana apple orange banana apple"
words = text.split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq)2. Common Elements in Two Lists (Set)
list1 = [1,2,3,4]
list2 = [3,4,5,6]
common = set(list1) & set(list2)
print(common) # {3,4}β‘ Intermediate Level
3. File Copy (with error handling)
try:
with open("source.txt","r") as src, open("dest.txt","w") as dest:
dest.write(src.read())
print("Copied.")
except FileNotFoundError:
print("Source file missing.")Unsolved Exercises
π° Beginner
1. Student Grades Dictionary
Create dict from 3 student names & marks. Print average marks.
2. Unique Characters (Set)
Input a word, print the set of unique letters.
β‘ Intermediate
3. JSON-like file reader
Read a file where each line is "key:value", store in dict.