Collections
Dictionaries
Key-Value Storage
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.
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()
main()
37main()38#@help createphone_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 ===for name, number in phone_book.items():
pass 1 of 633print("\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-1234All 6 passes — pass 1 is the card above pass namenumber1 Alice 555-1234 2 Bob 555-5678 3 Carol 555-9999 4 David 555-1111 5 Eve 555-2222 6 Frank 555-3333 main()
37main()38#@help create
{key: value} creates a dict. Use d[key] to access values.
Look up a contact
Retrieve a value by its key.
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()
main()
42main()43#@help getinventory ← {'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: Bananasif stock is not None: #?check
25if stock30 is not None: #?check26 print(f"In stock: {stock30} units")27 if stock < 35:outputIn stock: 30 unitsif 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!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 ===qty ← 50, status ← ✓ 50 in stock
pass 1 of 437for 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 stockAll 4 passes — pass 1 is the card above pass check_itemqtystatus1 Apples 50 ✓ 50 in stock 2 Mangoes 0 ✗ Not available 3 Oranges 25 ✓ 25 in stock 4 Pears 0 ✗ Not available main()
42main()43#@help get
main()
41main()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: Mangoeselse:
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']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 ===qty ← 50, status ← ✓ 50 in stock
pass 1 of 436for 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 stockAll 4 passes — pass 1 is the card above pass check_itemqtystatus1 Apples 50 ✓ 50 in stock 2 Mangoes 0 ✗ Not available 3 Oranges 25 ✓ 25 in stock 4 Pears 0 ✗ Not available main()
41main()
d[key] raises KeyError if missing. Use d.get(key) for safe access.
Update an entry
Change the value associated with a key.
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()
main()
48main()49#@help updateinventory ← {'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 ===word_count ← {'apple': 1}, word_count[word] ← 1
pass 1 of 737for 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 pass wordword_countword_count[word]1 apple {} → {'apple': 1} 1 2 banana {'apple': 1} → {'apple': 1, 'banana': 1} 1 3 apple {'apple': 1, 'banana': 1} → {'apple': 2, 'banana': 1} 2 4 orange {'apple': 2, 'banana': 1} → {'apple': 2, 'banana': 1, 'orange': 1} 1 5 apple {'apple': 2, 'banana': 1, 'orange': 1} → {'apple': 3, 'banana': 1, 'orange': 1} 3 6 banana {'apple': 3, 'banana': 1, 'orange': 1} → {'apple': 3, 'banana': 2, 'orange': 1} 2 7 grape {'apple': 3, 'banana': 2, 'orange': 1} → {'apple': 3, 'banana': 2, 'orange': 1, 'grape': 1} 1 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}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.
Check if key exists
Test whether a key is in the dict before accessing.
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()
main()
46main()47#@help inuser_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: bobcorrect_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 foundif 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 successfulweak_password ← pass123
34# Check if value exists (less common) #?valuein35print("\n=== Security Check ===")36weak_password→ pass123 = "pass123"output === Security Check ===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!for user, pwd in user_passwords.items():
pass 1 of 341# 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 pass userpwdweak_password1 alice pass123 pass123 2 bob secret456 — 3 carol hunter2 — 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: alicemain()
46main()47#@help in
main()
45main()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: eveelse:
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?weak_password ← pass123
33# Check if value exists (less common)34print("\n=== Security Check ===")35weak_password→ pass123 = "pass123"output === Security Check ===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!for user, pwd in user_passwords.items():
pass 1 of 340# 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 pass userpwdweak_password1 alice pass123 pass123 2 bob secret456 — 3 carol hunter2 — 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: alicemain()
45main()
key in d is O(1) - use it to avoid KeyError.
Iterate through entries
Loop through keys, values, or key-value pairs.
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()
main()
49main()50#@help keysprices ← {'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:for item in prices: # Or: prices.keys()
pass 1 of 513print("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 • CoffeeAll 5 passes — pass 1 is the card above pass item1 Coffee 2 Tea 3 Juice 4 Water 5 Soda total ← 0
17# Method 2: Iterate values only #?values18print("\n2. Values only:")19total→ 0 = 020for price in prices.values():output 2. Values only:total ← 4.5
pass 1 of 519total = 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.50All 5 passes — pass 1 is the card above pass pricetotal1 4.5 0 → 4.5 2 3.0 4.5 → 7.5 3 5.25 7.5 → 12.75 4 1.5 12.75 → 14.25 5 2.75 14.25 → 17.0 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()):for item, price in prices.items():
pass 1 of 526print("\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.50All 5 passes — pass 1 is the card above pass itemprice1 Coffee 4.5 2 Tea 3.0 3 Juice 5.25 4 Water 1.5 5 Soda 2.75 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:for i, (item, price) in enumerate(prices.items(), 1):
pass 1 of 531print("\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.50All 5 passes — pass 1 is the card above pass iitemprice1 1 Coffee 4.5 2 2 Tea 3.0 3 3 Juice 5.25 4 4 Water 1.5 5 5 Soda 2.75 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.40main()
49main()50#@help keys
Use d.keys(), d.values(), or d.items() for different views.
Exercise: dict_comprehension.py
Create dictionaries with comprehension syntax