Warmup

Assign to variable position a tuple of coordinates (1, 5) and then unpack it into variables x and y.

Admin

  • Due today: Assignment 3.4, PE 1 Module 3 Quiz
  • Do today: Assignment 3.5
  • Tomorrow, Friday 9/12:
    • PE 1 Module 3 Test
    • Unit 3 Quiz on paper: lists, tuples and dictionaries

Lesson 3.5 – Dictionaries: Basics

What we’ll learn today

  • What a dictionary is
  • How to create dictionaries
  • Accessing values with keys
  • Adding and removing items

Quick Review

  • What is the main difference between a tuple and a list?
  • Can you change values inside a tuple?

Dictionary Basics

  • A dictionary stores key–value pairs.
student = {
    "name": "Alice",
    "age": 16,
    "grade": "10th"
}

Accessing Values

  • Use the key inside square brackets.
print(student["name"])   # Alice

Adding Items

student["gpa"] = 3.8
print(student)

Changing Values

student["age"] = 17
print(student)

Removing Items

del student["grade"]
print(student)

Class Question

  • How is a dictionary different from a list?

Membership with Keys

  • You can test if a key exists.
if "name" in student:
    print("Yes, we have a name!")

Mini Practice

  1. Create a dictionary for a pet with keys type, name, and age.
  2. Print just the name.
  3. Add a new key color.
  4. Print the full dictionary.

Mini Challenge

  • Write a program that:
    1. Creates a dictionary for a book: title, author, year
    2. Prints the author
    3. Adds the number of pages
    4. Removes the year