You're building a phone book. Given a name, you need the phone number instantly. Lists require searching through every entry. Dictionaries give you direct lookup by key - O(1) instead of O(n).

Create a phone book

Store name-to-number associations.

phone_book.py
Replay: real traced execution (multi-file project)
def main():
    # Create a phone book dictionary
    phone_book = {}

    print("=== Building Phone Book ===")

    # Add contacts
    phone_book["Alice"] = "555-1234"
    print(f"Added Alice: {phone_book}")

    phone_book["Bob"] = "555-5678"
    print(f"Added Bob: {phone_book}")

    phone_book["Carol"] = "555-9999"
    print(f"Added Carol: {phone_book}")

    # Add more contacts
    phone_book["David"] = "555-1111"
    phone_book["Eve"] = "555-2222"
    phone_book["Frank"] = "555-3333"
    print(f"\nWith more contacts: {phone_book}")

    print("\n=== Phone Book Contents ===")
    print(f"Total contacts: {len(phone_book)}")

    # Look up a number
    name = "Bob"
    number = phone_book[name]
    print(f"\n{name}'s number: {number}")

    # Display all contacts
    print("\n=== All Contacts ===")
    for name, number in phone_book.items():
        print(f"{name}: {number}")

main()
  1. main()

    37main()38#@help create
  2. phone_book ← {}, phone_book[”Alice”] ← 555-1234, phone_book[”Bob”] ← 555-5678

    1#@var=default,moreContacts2def main():3    # Create a phone book dictionary  #?create4    phone_book→ {} = {}5    6    print("=== Building Phone Book ===")7    8    # Add contacts  #?add9    phone_book["Alice"]→ 555-1234 = "555-1234"10    print(f"Added Alice: {phone_book{'Alice': '555-1234'}}")11    12    phone_book["Bob"]→ 555-5678 = "555-5678"13    print(f"Added Bob: {phone_book{'Alice': '555-1234', 'Bob': '555-5678'}}")14    15    phone_book["Carol"]→ 555-9999 = "555-9999"16    print(f"Added Carol: {phone_book{'Alice': '555-1234', 'Bob': '555-5678', 'Carol': '555-9999'}}")17    18    # Add more contacts19    phone_book["David"]→ 555-1111 = "555-1111"  #@var=_,!20    phone_book["Eve"]→ 555-2222 = "555-2222"    #@var=_,!21    phone_book["Frank"]→ 555-3333 = "555-3333"  #@var=_,!22    print(f"\nWith more contacts: {phone_book{'Alice': '555-1234', 'Bob': '555-5678', 'Carol': '555-9999', 'David': '555-1111', 'Eve': '555-2222', 'Frank': '555-3333'}}")  #@var=_,!23    24    print("\n=== Phone Book Contents ===")25    print(f"Total contacts: {len(phone_book{'Alice': '555-1234', 'Bob': '555-5678', 'Carol': '555-9999', 'David': '555-1111', 'Eve': '555-2222', 'Frank': '555-3333'})}")26    27    # Look up a number  #?lookup28    name→ Bob = "Bob"29    number→ 555-5678 = phone_book[name]555-567830    print(f"\n{nameBob}'s number: {number555-5678}")31    32    # Display all contacts33    print("\n=== All Contacts ===")34    for name, number in phone_book.items():
    output=== Building Phone Book ===
    Added Alice: {'Alice': '555-1234'}
    Added Bob: {'Alice': '555-1234', 'Bob': '555-5678'}
    Added Carol: {'Alice': '555-1234', 'Bob': '555-5678', 'Carol': '555-9999'}
    
    With more contacts: {'Alice': '555-1234', 'Bob': '555-5678', 'Carol': '555-9999', 'David': '555-1111', 'Eve': '555-2222', 'Frank': '555-3333'}
    
    === Phone Book Contents ===
    Total contacts: 6
    
    Bob's number: 555-5678
    
    === All Contacts ===
  3. for name, number in phone_book.items():

    pass 1 of 6
    33print("\n=== All Contacts ===")34for nameAlice, number555-1234 in phone_book{'Alice': '555-1234', 'Bob': '555-5678', 'Carol': '555-9999', 'David': '555-1111', 'Eve': '555-2222', 'Frank': '555-3333'}.items():35    print(f"{nameAlice}: {number555-1234}")
    outputAlice: 555-1234
    All 6 passes — pass 1 is the card above
    passnamenumber
    1Alice555-1234
    2Bob555-5678
    3Carol555-9999
    4David555-1111
    5Eve555-2222
    6Frank555-3333
  4. main()

    37main()38#@help create

{key: value} creates a dict. Use d[key] to access values.

dict Key-value pairs with O(1) lookup. Keys must be unique and hashable.

Look up a contact

Retrieve a value by its key.

item
lookup.py
Replay: real traced execution (multi-file project)
def main():
    inventory = {
        "Apples": 50,
        "Bananas": 30,
        "Oranges": 25,
        "Grapes": 40
    }

    print("=== Store Inventory ===")
    print(inventory)

    # Look up existing item
    item = "Bananas"

    print("\n=== Inventory Lookup ===")
    print(f"Looking for: {item}")

    # UNSAFE: Direct access raises KeyError if missing!
    # stock = inventory[item]  # Would crash if item not found

    # SAFE: Use .get() method
    stock = inventory.get(item)

    if stock is not None:
        print(f"In stock: {stock} units")
        if stock < 35:
            print("⚠️ Low stock - consider reordering!")
    else:
        print("❌ Item not found in inventory!")
        print(f"Available items: {list(inventory.keys())}")

    # Using .get() with default value
    print("\n=== Using .get() with default ===")
    check_items = ["Apples", "Mangoes", "Oranges", "Pears"]

    for check_item in check_items:
        qty = inventory.get(check_item, 0)  # 0 if not found
        status = f"✓ {qty} in stock" if qty > 0 else "✗ Not available"
        print(f"{check_item}: {status}")

main()
def main():
    inventory = {
        "Apples": 50,
        "Bananas": 30,
        "Oranges": 25,
        "Grapes": 40
    }

    print("=== Store Inventory ===")
    print(inventory)

    # Look up existing item
    item = "Mangoes"

    print("\n=== Inventory Lookup ===")
    print(f"Looking for: {item}")

    # UNSAFE: Direct access raises KeyError if missing!
    # stock = inventory[item]  # Would crash if item not found

    # SAFE: Use .get() method
    stock = inventory.get(item)

    if stock is not None:
        print(f"In stock: {stock} units")
        if stock < 35:
            print("⚠️ Low stock - consider reordering!")
    else:
        print("❌ Item not found in inventory!")
        print(f"Available items: {list(inventory.keys())}")

    # Using .get() with default value
    print("\n=== Using .get() with default ===")
    check_items = ["Apples", "Mangoes", "Oranges", "Pears"]

    for check_item in check_items:
        qty = inventory.get(check_item, 0)  # 0 if not found
        status = f"✓ {qty} in stock" if qty > 0 else "✗ Not available"
        print(f"{check_item}: {status}")

main()
  1. main()

    42main()43#@help get
  2. inventory ← {'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40}

    1#@var=default,missing2def main():3    inventory→ {'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40} = {4        "Apples": 50,5        "Bananas": 30,6        "Oranges": 25,7        "Grapes": 408    }9    10    print("=== Store Inventory ===")11    print(inventory{'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40})12    13    # Look up existing item14    item→ Bananas = "Bananas"  #@var=_,Mangoes15    16    print("\n=== Inventory Lookup ===")17    print(f"Looking for: {itemBananas}")18    19    # UNSAFE: Direct access raises KeyError if missing!20    # stock = inventory[item]  # Would crash if item not found21    22    # SAFE: Use .get() method  #?get23    stock→ 30 = inventory{'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40}.get(itemBananas)
    output=== Store Inventory ===
    {'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40}
    
    === Inventory Lookup ===
    Looking for: Bananas
  3. if stock is not None: #?check

    25if stock30 is not None:  #?check26    print(f"In stock: {stock30} units")27    if stock < 35:
    outputIn stock: 30 units
  4. if stock < 35:

    26    print(f"In stock: {stock} units")27    if stock30 < 35:28        print("⚠️ Low stock - consider reordering!")29else:
    output⚠️ Low stock - consider reordering!
  5. check_items ← ['Apples', 'Mangoes', 'Oranges', 'Pears']

    33# Using .get() with default value  #?default34print("\n=== Using .get() with default ===")35check_items→ ['Apples', 'Mangoes', 'Oranges', 'Pears'] = ["Apples", "Mangoes", "Oranges", "Pears"]
    output
    === Using .get() with default ===
  6. qty ← 50, status ← ✓ 50 in stock

    pass 1 of 4
    37for check_itemApples in check_items['Apples', 'Mangoes', 'Oranges', 'Pears']:38    qty→ 50 = inventory{'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40}.get(check_itemApples, 0)  # 0 if not found39    status→ ✓ 50 in stock = f"✓ {qty50} in stock" if qty > 0 else "✗ Not available"40    print(f"{check_itemApples}: {status✓ 50 in stock}")
    outputApples: ✓ 50 in stock
    All 4 passes — pass 1 is the card above
    passcheck_itemqtystatus
    1Apples50✓ 50 in stock
    2Mangoes0✗ Not available
    3Oranges25✓ 25 in stock
    4Pears0✗ Not available
  7. main()

    42main()43#@help get
  1. main()

    41main()
  2. inventory ← {'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40}

    1def main():2    inventory→ {'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40} = {3        "Apples": 50,4        "Bananas": 30,5        "Oranges": 25,6        "Grapes": 407    }8    9    print("=== Store Inventory ===")10    print(inventory{'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40})11    12    # Look up existing item13    item→ Mangoes = "Mangoes"14    15    print("\n=== Inventory Lookup ===")16    print(f"Looking for: {itemMangoes}")17    18    # UNSAFE: Direct access raises KeyError if missing!19    # stock = inventory[item]  # Would crash if item not found20    21    # SAFE: Use .get() method22    stock→ None = inventory{'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40}.get(itemMangoes)
    output=== Store Inventory ===
    {'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40}
    
    === Inventory Lookup ===
    Looking for: Mangoes
  3. else:

    26    if stock < 35:27        print("⚠️ Low stock - consider reordering!")28else:29    print("❌ Item not found in inventory!")30    print(f"Available items: {list(inventory{'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40}.keys())}")
    output❌ Item not found in inventory!
    Available items: ['Apples', 'Bananas', 'Oranges', 'Grapes']
  4. check_items ← ['Apples', 'Mangoes', 'Oranges', 'Pears']

    32# Using .get() with default value33print("\n=== Using .get() with default ===")34check_items→ ['Apples', 'Mangoes', 'Oranges', 'Pears'] = ["Apples", "Mangoes", "Oranges", "Pears"]
    output
    === Using .get() with default ===
  5. qty ← 50, status ← ✓ 50 in stock

    pass 1 of 4
    36for check_itemApples in check_items['Apples', 'Mangoes', 'Oranges', 'Pears']:37    qty→ 50 = inventory{'Apples': 50, 'Bananas': 30, 'Oranges': 25, 'Grapes': 40}.get(check_itemApples, 0)  # 0 if not found38    status→ ✓ 50 in stock = f"✓ {qty50} in stock" if qty > 0 else "✗ Not available"39    print(f"{check_itemApples}: {status✓ 50 in stock}")
    outputApples: ✓ 50 in stock
    All 4 passes — pass 1 is the card above
    passcheck_itemqtystatus
    1Apples50✓ 50 in stock
    2Mangoes0✗ Not available
    3Oranges25✓ 25 in stock
    4Pears0✗ Not available
  6. main()

    41main()

d[key] raises KeyError if missing. Use d.get(key) for safe access.

get Safe lookup: `d.get(key)` returns None if missing. `d.get(key, default)` for default.

Update an entry

Change the value associated with a key.

update_entry.py
Replay: real traced execution (multi-file project)
def main():
    inventory = {
        "Apples": 50,
        "Bananas": 30,
        "Oranges": 25
    }

    print("=== Initial Inventory ===")
    print(inventory)

    # Update: Restock apples
    item = "Apples"
    add_amount = 20

    old_stock = inventory[item]
    inventory[item] = old_stock + add_amount  # Direct update

    print("\n=== After Restocking ===")
    print(f"{item}: {old_stock} → {inventory[item]}")
    print(inventory)

    # Sell some items
    item = "Bananas"
    sold = 5
    inventory[item] -= sold
    print(f"\nSold {sold} {item}")
    print(inventory)

    # Word frequency counter
    print("\n=== Word Frequency Counter ===")
    text = "apple banana apple orange apple banana grape"
    words = text.split()

    word_count = {}

    for word in words:
        # Get current count (0 if not seen), add 1
        word_count[word] = word_count.get(word, 0) + 1

    print(f'Text: "{text}"')
    print(f"Word counts: {word_count}")

    # Pythonic alternative: collections.Counter
    from collections import Counter
    print(f"Using Counter: {dict(Counter(words))}")

main()
  1. main()

    48main()49#@help update
  2. inventory ← {'Apples': 50, 'Bananas': 30, 'Oranges': 25}, item ← Apples

    1#@var=default,counter2def main():3    inventory→ {'Apples': 50, 'Bananas': 30, 'Oranges': 25} = {4        "Apples": 50,5        "Bananas": 30,6        "Oranges": 257    }8    9    print("=== Initial Inventory ===")10    print(inventory{'Apples': 50, 'Bananas': 30, 'Oranges': 25})11    12    # Update: Restock apples  #?update13    item→ Apples = "Apples"14    add_amount→ 20 = 2015    16    old_stock→ 50 = inventory[item]5017    inventory[item]→ 70 = old_stock50 + add_amount20  # Direct update18    19    print("\n=== After Restocking ===")20    print(f"{itemApples}: {old_stock50} → {inventory[item]70}")21    print(inventory{'Apples': 70, 'Bananas': 30, 'Oranges': 25})22    23    # Sell some items24    item→ Bananas = "Bananas"  #@var=_,!25    sold→ 5 = 5  #@var=_,!26    inventory[item]→ 25 -= sold5  #@var=_,!27    print(f"\nSold {sold5} {itemBananas}")  #@var=_,!28    print(inventory{'Apples': 70, 'Bananas': 25, 'Oranges': 25})  #@var=_,!29    30    # Word frequency counter  #?freq  #@var=!,_31    print("\n=== Word Frequency Counter ===")  #@var=!,_32    text→ apple banana apple orange apple banana grape = "apple banana apple orange apple banana grape"  #@var=!,_33    words→ ['apple', 'banana', 'apple', 'orange', 'apple', 'banana', 'grape'] = textapple banana apple orange apple banana grape.split()  #@var=!,_34    35    word_count→ {} = {}  #@var=!,_
    output=== Initial Inventory ===
    {'Apples': 50, 'Bananas': 30, 'Oranges': 25}
    
    === After Restocking ===
    Apples: 50 → 70
    {'Apples': 70, 'Bananas': 30, 'Oranges': 25}
    
    Sold 5 Bananas
    {'Apples': 70, 'Bananas': 25, 'Oranges': 25}
    
    === Word Frequency Counter ===
  3. word_count ← {'apple': 1}, word_count[word] ← 1

    pass 1 of 7
    37for wordapple in words['apple', 'banana', 'apple', 'orange', 'apple', 'banana', 'grape']:  #@var=!,_38    # Get current count (0 if not seen), add 1  #@var=!,_39    word_count[word]→ 1 = word_count→ {'apple': 1}.get(wordapple, 0) + 1  #@var=!,_
    All 7 passes — pass 1 is the card above
    passwordword_countword_count[word]
    1apple{} {'apple': 1}1
    2banana{'apple': 1} {'apple': 1, 'banana': 1}1
    3apple{'apple': 1, 'banana': 1} {'apple': 2, 'banana': 1}2
    4orange{'apple': 2, 'banana': 1} {'apple': 2, 'banana': 1, 'orange': 1}1
    5apple{'apple': 2, 'banana': 1, 'orange': 1} {'apple': 3, 'banana': 1, 'orange': 1}3
    6banana{'apple': 3, 'banana': 1, 'orange': 1} {'apple': 3, 'banana': 2, 'orange': 1}2
    7grape{'apple': 3, 'banana': 2, 'orange': 1} {'apple': 3, 'banana': 2, 'orange': 1, 'grape': 1}1
  4. print(f'Text: "{text}"') #@var=!,_

    41print(f'Text: "{textapple banana apple orange apple banana grape}"')  #@var=!,_42print(f"Word counts: {word_count{'apple': 3, 'banana': 2, 'orange': 1, 'grape': 1}}")  #@var=!,_4344# Pythonic alternative: collections.Counter  #@var=!,_45from collections import Counter  #@var=!,_46print(f"Using Counter: {dict(Counter(words['apple', 'banana', 'apple', 'orange', 'apple', 'banana', 'grape']))}")  #@var=!,_
    outputText: "apple banana apple orange apple banana grape"
    Word counts: {'apple': 3, 'banana': 2, 'orange': 1, 'grape': 1}
    Using Counter: {'apple': 3, 'banana': 2, 'orange': 1, 'grape': 1}
  5. main()

    48main()49#@help update

d[key] = value updates if exists, adds if new.

See Dictionary Mutation

A dictionary update changes the value stored under one key. These diagrams pin the exact inventory and phone-book examples.

Inventory values after each dictionary updateInventory values after each dictionary updatestepApplesBananasOrangesstart503025+20 Apples703025-5 Bananas702525
Restocking apples changes `Apples` from 50 to 70. Selling 5 bananas changes `Bananas` from 30 to 25.
Adding keys grows the phone bookAdding keys grows the phone book{}Alice:555-1234+ Bob:555-5678+ Carol:555-9999
Each `phone_book[name] = number` assignment adds one key-value entry because the key is not already present.

Check if key exists

Test whether a key is in the dict before accessing.

username
check_key.py
Replay: real traced execution (multi-file project)
def main():
    user_passwords = {
        "alice": "pass123",
        "bob": "secret456",
        "carol": "hunter2"
    }

    print("=== Login System ===")
    print(f"Registered users: {list(user_passwords.keys())}")

    # Login attempt
    username = "bob"
    password = "secret456"

    print("\n=== Login Attempt ===")
    print(f"Username: {username}")

    # Check if user exists
    if username in user_passwords:
        print("✓ User found")

        # Verify password
        correct_password = user_passwords[username]
        if correct_password == password:
            print("✓ Password correct")
            print("🎉 Login successful!")
        else:
            print("✗ Incorrect password")
    else:
        print("✗ User not found")
        print("Would you like to register?")

    # Check if value exists (less common)
    print("\n=== Security Check ===")
    weak_password = "pass123"

    if weak_password in user_passwords.values():
        print("⚠️ Someone is using a weak password!")

        # Find which user (need to iterate)
        for user, pwd in user_passwords.items():
            if pwd == weak_password:
                print(f"User with weak password: {user}")

main()
def main():
    user_passwords = {
        "alice": "pass123",
        "bob": "secret456",
        "carol": "hunter2"
    }

    print("=== Login System ===")
    print(f"Registered users: {list(user_passwords.keys())}")

    # Login attempt
    username = "eve"
    password = "secret456"

    print("\n=== Login Attempt ===")
    print(f"Username: {username}")

    # Check if user exists
    if username in user_passwords:
        print("✓ User found")

        # Verify password
        correct_password = user_passwords[username]
        if correct_password == password:
            print("✓ Password correct")
            print("🎉 Login successful!")
        else:
            print("✗ Incorrect password")
    else:
        print("✗ User not found")
        print("Would you like to register?")

    # Check if value exists (less common)
    print("\n=== Security Check ===")
    weak_password = "pass123"

    if weak_password in user_passwords.values():
        print("⚠️ Someone is using a weak password!")

        # Find which user (need to iterate)
        for user, pwd in user_passwords.items():
            if pwd == weak_password:
                print(f"User with weak password: {user}")

main()
  1. main()

    46main()47#@help in
  2. user_passwords ← {'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'}

    1#@var=default,notFound2def main():3    user_passwords→ {'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'} = {4        "alice": "pass123",5        "bob": "secret456",6        "carol": "hunter2"7    }8    9    print("=== Login System ===")10    print(f"Registered users: {list(user_passwords{'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'}.keys())}")11    12    # Login attempt13    username→ bob = "bob"  #@var=_,eve14    password→ secret456 = "secret456"15    16    print("\n=== Login Attempt ===")17    print(f"Username: {usernamebob}")
    output=== Login System ===
    Registered users: ['alice', 'bob', 'carol']
    
    === Login Attempt ===
    Username: bob
  3. correct_password ← secret456

    19# Check if user exists  #?in20if usernamebob in user_passwords{'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'}:21    print("✓ User found")22    23    # Verify password24    correct_password→ secret456 = user_passwords[username]secret45625    if correct_password == password:
    output✓ User found
  4. if correct_password == password:

    24correct_password = user_passwords[username]25if correct_passwordsecret456 == passwordsecret456:26    print("✓ Password correct")27    print("🎉 Login successful!")28else:
    output✓ Password correct
    🎉 Login successful
  5. weak_password ← pass123

    34# Check if value exists (less common)  #?valuein35print("\n=== Security Check ===")36weak_password→ pass123 = "pass123"
    output
    === Security Check ===
  6. if weak_password in user_passwords.values():

    38if weak_passwordpass123 in user_passwords{'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'}.values():39    print("⚠️ Someone is using a weak password!")
    output⚠️ Someone is using a weak password!
  7. for user, pwd in user_passwords.items():

    pass 1 of 3
    41# Find which user (need to iterate)42for useralice, pwdpass123 in user_passwords{'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'}.items():43    if pwd == weak_password:44        print(f"User with weak password: {user}")
    All 3 passes — pass 1 is the card above
    passuserpwdweak_password
    1alicepass123pass123
    2bobsecret456
    3carolhunter2
  8. if pwd == weak_password:

    42for user, pwd in user_passwords.items():43    if pwdpass123 == weak_passwordpass123:44        print(f"User with weak password: {useralice}")
    outputUser with weak password: alice
  9. main()

    46main()47#@help in
  1. main()

    45main()
  2. user_passwords ← {'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'}

    1def main():2    user_passwords→ {'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'} = {3        "alice": "pass123",4        "bob": "secret456",5        "carol": "hunter2"6    }7    8    print("=== Login System ===")9    print(f"Registered users: {list(user_passwords{'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'}.keys())}")10    11    # Login attempt12    username→ eve = "eve"13    password→ secret456 = "secret456"14    15    print("\n=== Login Attempt ===")16    print(f"Username: {usernameeve}")
    output=== Login System ===
    Registered users: ['alice', 'bob', 'carol']
    
    === Login Attempt ===
    Username: eve
  3. else:

    27    else:28        print("✗ Incorrect password")29else:30    print("✗ User not found")31    print("Would you like to register?")
    output✗ User not found
    Would you like to register?
  4. weak_password ← pass123

    33# Check if value exists (less common)34print("\n=== Security Check ===")35weak_password→ pass123 = "pass123"
    output
    === Security Check ===
  5. if weak_password in user_passwords.values():

    37if weak_passwordpass123 in user_passwords{'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'}.values():38    print("⚠️ Someone is using a weak password!")
    output⚠️ Someone is using a weak password!
  6. for user, pwd in user_passwords.items():

    pass 1 of 3
    40# Find which user (need to iterate)41for useralice, pwdpass123 in user_passwords{'alice': 'pass123', 'bob': 'secret456', 'carol': 'hunter2'}.items():42    if pwd == weak_password:43        print(f"User with weak password: {user}")
    All 3 passes — pass 1 is the card above
    passuserpwdweak_password
    1alicepass123pass123
    2bobsecret456
    3carolhunter2
  7. if pwd == weak_password:

    41for user, pwd in user_passwords.items():42    if pwdpass123 == weak_passwordpass123:43        print(f"User with weak password: {useralice}")
    outputUser with weak password: alice
  8. main()

    45main()

key in d is O(1) - use it to avoid KeyError.

in Membership test: `key in d`. Returns True/False in O(1) time.

Iterate through entries

Loop through keys, values, or key-value pairs.

iterate_dict.py
Replay: real traced execution (multi-file project)
def main():
    prices = {
        "Coffee": 4.50,
        "Tea": 3.00,
        "Juice": 5.25,
        "Water": 1.50,
        "Soda": 2.75
    }

    print("=== Café Menu ===\n")

    # Method 1: Iterate keys only
    print("1. Keys only:")
    for item in prices:  # Or: prices.keys()
        print(f"   • {item}")

    # Method 2: Iterate values only
    print("\n2. Values only:")
    total = 0
    for price in prices.values():
        total += price
        print(f"   ${price:.2f}")
    print(f"   Total: ${total:.2f}")

    # Method 3: Iterate both with .items() - MOST COMMON
    print("\n3. Keys and Values (.items()):")
    for item, price in prices.items():
        print(f"   {item:<10} ${price:.2f}")

    # Method 4: Enumerate with items (if you need index)
    print("\n4. With index:")
    for i, (item, price) in enumerate(prices.items(), 1):
        print(f"   {i}. {item}: ${price:.2f}")

    # Find min and max priced items
    print("\n=== Price Analysis ===")

    # Pythonic: use min/max with key parameter
    cheapest = min(prices, key=prices.get)
    expensive = max(prices, key=prices.get)

    print(f"Cheapest: {cheapest} (${prices[cheapest]:.2f})")
    print(f"Most expensive: {expensive} (${prices[expensive]:.2f})")

    # Average price
    avg = sum(prices.values()) / len(prices)
    print(f"Average price: ${avg:.2f}")

main()
  1. main()

    49main()50#@help keys
  2. prices ← {'Coffee': 4.5, 'Tea': 3.0, 'Juice': 5.25, 'Water': 1.5, 'Soda': 2.75}

    1def main():2    prices→ {'Coffee': 4.5, 'Tea': 3.0, 'Juice': 5.25, 'Water': 1.5, 'Soda': 2.75} = {3        "Coffee": 4.50,4        "Tea": 3.00,5        "Juice": 5.25,6        "Water": 1.50,7        "Soda": 2.758    }9    10    print("=== Café Menu ===\n")11    12    # Method 1: Iterate keys only  #?keys13    print("1. Keys only:")14    for item in prices:  # Or: prices.keys()
    output=== Café Menu ===
    1. Keys only:
  3. for item in prices: # Or: prices.keys()

    pass 1 of 5
    13print("1. Keys only:")14for itemCoffee in prices{'Coffee': 4.5, 'Tea': 3.0, 'Juice': 5.25, 'Water': 1.5, 'Soda': 2.75}:  # Or: prices.keys()15    print(f"   • {itemCoffee}")
    output   • Coffee
    All 5 passes — pass 1 is the card above
    passitem
    1Coffee
    2Tea
    3Juice
    4Water
    5Soda
  4. total ← 0

    17# Method 2: Iterate values only  #?values18print("\n2. Values only:")19total→ 0 = 020for price in prices.values():
    output
    2. Values only:
  5. total ← 4.5

    pass 1 of 5
    19total = 020for price4.5 in prices{'Coffee': 4.5, 'Tea': 3.0, 'Juice': 5.25, 'Water': 1.5, 'Soda': 2.75}.values():21    total→ 4.5 += price4.522    print(f"   ${price4.5:.2f}")23print(f"   Total: ${total:.2f}")
    output   $4.50
    All 5 passes — pass 1 is the card above
    passpricetotal
    14.50 4.5
    23.04.5 7.5
    35.257.5 12.75
    41.512.75 14.25
    52.7514.25 17.0
  6. print(f" Total: ${total:.2f}")

    22    print(f"   ${price:.2f}")23print(f"   Total: ${total17.0:.2f}")2425# Method 3: Iterate both with .items() - MOST COMMON  #?items26print("\n3. Keys and Values (.items()):")27for item, price in prices.items():
    output   Total: $17.00
    
    3. Keys and Values (.items()):
  7. for item, price in prices.items():

    pass 1 of 5
    26print("\n3. Keys and Values (.items()):")27for itemCoffee, price4.5 in prices{'Coffee': 4.5, 'Tea': 3.0, 'Juice': 5.25, 'Water': 1.5, 'Soda': 2.75}.items():28    print(f"   {itemCoffee:<10} ${price4.5:.2f}")
    output   Coffee     $4.50
    All 5 passes — pass 1 is the card above
    passitemprice
    1Coffee4.5
    2Tea3.0
    3Juice5.25
    4Water1.5
    5Soda2.75
  8. print(" 4. With index:")

    30# Method 4: Enumerate with items (if you need index)31print("\n4. With index:")32for i, (item, price) in enumerate(prices.items(), 1):
    output
    4. With index:
  9. for i, (item, price) in enumerate(prices.items(), 1):

    pass 1 of 5
    31print("\n4. With index:")32for i1, (itemCoffee, price4.5) in enumerate(prices{'Coffee': 4.5, 'Tea': 3.0, 'Juice': 5.25, 'Water': 1.5, 'Soda': 2.75}.items(), 1):33    print(f"   {i1}. {itemCoffee}: ${price4.5:.2f}")
    output   1. Coffee: $4.50
    All 5 passes — pass 1 is the card above
    passiitemprice
    11Coffee4.5
    22Tea3.0
    33Juice5.25
    44Water1.5
    55Soda2.75
  10. cheapest ← Water, expensive ← Juice, avg ← 3.4

    35# Find min and max priced items  #?minmax36print("\n=== Price Analysis ===")3738# Pythonic: use min/max with key parameter39cheapest→ Water = min(prices{'Coffee': 4.5, 'Tea': 3.0, 'Juice': 5.25, 'Water': 1.5, 'Soda': 2.75}, key=prices.get⟨built-in method get of dict A⟩)40expensive→ Juice = max(prices{'Coffee': 4.5, 'Tea': 3.0, 'Juice': 5.25, 'Water': 1.5, 'Soda': 2.75}, key=prices.get⟨built-in method get of dict A⟩)4142print(f"Cheapest: {cheapestWater} (${prices[cheapest]1.5:.2f})")43print(f"Most expensive: {expensiveJuice} (${prices[expensive]5.25:.2f})")4445# Average price46avg→ 3.4 = sum(prices{'Coffee': 4.5, 'Tea': 3.0, 'Juice': 5.25, 'Water': 1.5, 'Soda': 2.75}.values()) / len(prices)47print(f"Average price: ${avg3.4:.2f}")
    output
    === Price Analysis ===
    Cheapest: Water ($1.50)
    Most expensive: Juice ($5.25)
    Average price: $3.40
  11. main()

    49main()50#@help keys

Use d.keys(), d.values(), or d.items() for different views.

Exercise: dict_comprehension.py

Create dictionaries with comprehension syntax