Week 4 β€’ Python Course

Week 4: Dictionaries, Sets & File I/O

Store key-value pairs, work with unique collections, read and write files β€” plus remote collaboration on GitHub.

Week 4
1
2
3
4
5
6

πŸ“… 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.

01

Dictionaries

key value lookup
02
πŸ”’

Sets

unique union intersect
03
πŸ“‚

File I/O

read write open
04
πŸ“

More File I/O

with modes error
05
πŸ—‚οΈ

Mini Project

phonebook CRUD
06
πŸ”„

GitHub Collab

fetch merge conflict

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().

πŸ“– Dictionary Quick Reference Infographic
"name""Amit"
"age"14
"grade""A"

Creating & Accessing

day1_create.py
# 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

day1_modify.py
student["city"] = "Delhi"     # add
student["age"] = 15           # update
del student["grade"]          # delete
print(student) # {'name':'Amit','age':15,'city':'Delhi'}

Looping & Methods

day1_looping.py
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().

day1_exercise_solution.py
me = {"name": "Riya", "age": 13, "subject": "Math"}
for k, v in me.items():
    print(f"{k}: {v}")
πŸ’‘ Key takeaway: Dictionaries are unordered* (Python 3.7+ preserves insertion order). Use them for fast lookups by a unique key.

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().

πŸ”’ Set Operations Infographic
Union
A | B
All unique items
Intersection
A & B
Common items
Difference
A - B
In A not in B

Set Basics

day2_basics.py
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

day2_operations.py
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.

day2_exercise_solution.py
sentence = input("Enter a sentence: ")
words = sentence.split()
unique = set(words)
print(f"Unique words ({len(unique)}): {unique}")
⚠️ Note: Sets are unordered, so you cannot access by index. Convert to list if order matters.

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.

πŸ“‚ File Modes Infographic
'r'
read
'w'
write (overwrites)
'a'
append
'r+'
read+write

Writing to a File

day3_write.py
f = open("data.txt", "w")
f.write("Hello, Python!\n")
f.write("Week 4 is fun.")
f.close()

Reading from a File

day3_read.py
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

day3_append.py
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.

day3_exercise_solution.py
from datetime import datetime
entry = input("Log entry: ")
with open("log.txt", "a") as f:
    f.write(f"{datetime.now()}: {entry}\n")
print("Logged!")
πŸ’‘ Best Practice: Use 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)

day4_readlines.py
with open("bigfile.txt", "r") as f:
    for line in f:
        print(line.strip())

Writing a CSV (Comma-Separated)

day4_csv.py
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

day4_exceptions.py
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.

day4_exercise_solution.py
grades = {}
with open("students.csv", "r") as f:
    for line in f:
        name, age, grade = line.strip().split(',')
        grades[name] = grade
print(grades)
⚠️ Remember: Always close files. Prefer 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

  1. Load existing contacts from phonebook.txt (name,phone per line).
  2. Provide menu: 1. Add, 2. Search, 3. Delete, 4. View all, 5. Save & Exit.
  3. Use a dictionary: name β†’ phone number.
  4. Use set operations to detect duplicate names before adding.
phonebook.py
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
πŸš€ Extension: Add input validation (phone numbers only digits), or a β€œlist duplicates” feature using a set.

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.

πŸ”„ Remote Collaboration Visual
πŸ’» Local
feature branch
⬆️ push
☁️ GitHub
⬇️ fetch
πŸ’» origin/main

fetch = download updates without merging | pull = fetch + merge

Important Commands

CommandPurpose
git fetch originDownload remote changes, don't integrate
git merge origin/mainMerge fetched changes into current branch
git pull origin mainFetch + merge in one step
git push origin featureUpload branch to remote

Resolving a Simple Conflict

Conflict occurs when two branches change the same line. Git marks the file like:

conflict_example.txt
<<<<<<< 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)

terminal simulation
# 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
πŸ’‘ Pro Tip: Always 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.

Write your solution here.
2. Unique Characters (Set)

Input a word, print the set of unique letters.

Write your solution here.

⚑ Intermediate

3. JSON-like file reader

Read a file where each line is "key:value", store in dict.

Write your solution here.