Warmup

  • Create a dictionary representing a pet with 2 key value pairs
  • Print one of the values
  • Add a new key

Agenda

  • Unit 3 Quiz 1
  • Lesson 3.6

Due Dates

Today

  • Assignment 3.5
  • PE 1 Module 3 Test

Monday

  • Assignment 3.6

Lesson 3.6 – Dictionaries: Iteration & Methods

What we’ll learn today

  • Looping through dictionaries
  • Dictionary methods (get, update, del)
  • Practical dictionary exercises

Quick Review

  • How do you add a new key to a dictionary?
  • How do you remove a key?

Looping Through Keys

student = {"name": "Alice", "age": 16, "grade": "10th"}
for key in student:
    print(key)

Looping Through Values

for value in student.values():
    print(value)

Looping Through Both

for key, value in student.items():
    print(key, ":", value)

Using get()

  • Safer than square brackets
print(student.get("name"))     # Alice
print(student.get("gpa", "N/A"))

Updating Dictionaries

student.update({"age": 17, "gpa": 3.9})
print(student)

Deleting Keys

del student["grade"]
print(student)

Class Question

  • Why might get() be safer than student["key"]?

Mini Practice

  1. Create a dictionary with 3 countries and their capitals.
  2. Loop through and print Country: Capital.

Mini Challenge

  • Write a program that:
    1. Creates a dictionary of 3 friends and their favorite foods
    2. Loops through to print each name and food
    3. Uses update() to change one food
    4. Prints the dictionary after the update