4. Functions, Dictionaries & Data Drills
Dictionaries & Nested Data (Storing Named Fields)
Store structured records like user profiles and products using Python dictionaries, avoid missing-key crashes with .get(), count items step by step, and read lists of dictionaries.
- Store and look up named fields using key-value dictionaries
- Prevent KeyError crashes on missing keys with .get()
- Count category totals and navigate lists of dictionaries
A list stores items by position (0, 1, 2). That works great for a shopping list—but imagine storing a user profile in a list: ["Alex", "alex@mail.com", 24, True].
Two weeks later, you have to remember: "Wait, was the email at position 1 or position 2?"
A dictionary (dict) fixes this by letting you label every piece of data with a name (key) instead of a position number!
Creating & Reading a Dictionary
Dictionaries use curly braces {...} with key: value pairs:
student = {
"name": "Alex",
"track": "Python",
"lessons_done": 9,
}
print(student["name"]) # Prints: Alex
print(student["lessons_done"]) # Prints: 9Look how clear student["name"] is compared to student[0]!
Adding, Updating & Deleting Fields
student["lessons_done"] = 10 # Updates an existing key
student["city"] = "Toronto" # Adds a brand-new key
student.pop("city") # Removes a keySafe Lookups with .get() (No More Crashes!)
What happens if you ask for student["streak"] when "streak" hasn't been added yet? Python crashes with KeyError: 'streak'.
Whenever a key might be missing, use .get(key, fallback_value) instead:
streak = student.get("streak", 0)
print(streak) # Prints: 0 (no crash!)Read student.get("streak", 0) as: "Look up 'streak'. If it exists, give me its value; if it's missing, just give me 0."
Looping Through a Dictionary
Use .items() to get both the key and the value together on every turn:
prices = {"Coffee": 4.50, "Bagel": 3.00, "Tea": 3.50}
for item, price in prices.items():
print(f"{item}: ${price:.2f}")Useful Real Pattern — Adding Totals by Category
Suppose you have a list of expenses and want to know how much you spent in each category (Food vs Travel):
expenses = [
{"item": "Lunch", "category": "Food", "amount": 12},
{"item": "Bus", "category": "Travel", "amount": 4},
{"item": "Coffee", "category": "Food", "amount": 5},
]
totals = {}
for e in expenses:
cat = e["category"]
totals[cat] = totals.get(cat, 0) + e["amount"]
print(totals) # {'Food': 17, 'Travel': 4}Let's trace how totals builds up step by step:
- Item 1 (Lunch, Food, $12):
totals.get("Food", 0)is0→0 + 12 = 12→totalsbecomes{"Food": 12} - Item 2 (Bus, Travel, $4):
totals.get("Travel", 0)is0→0 + 4 = 4→totalsbecomes{"Food": 12, "Travel": 4} - Item 3 (Coffee, Food, $5):
totals.get("Food", 0)is12→12 + 5 = 17→totalsbecomes{"Food": 17, "Travel": 4}!
Notice expenses above is a list of dictionaries—this exact shape is how almost every database and web API stores data!
Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Append a new expense {"item": "Notebook", "category": "Study", "amount": 8} to expenses and print the grand total of all expenses ($29).
Quick Checkpoints
Why is profile.get('phone', 'None') safer than profile['phone']?