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.

3 min readUpdated 2026-11-29
In This Lesson
  • 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:

python
student = {
    "name": "Alex",
    "track": "Python",
    "lessons_done": 9,
}

print(student["name"])          # Prints: Alex
print(student["lessons_done"])  # Prints: 9

Look how clear student["name"] is compared to student[0]!

Adding, Updating & Deleting Fields

python
student["lessons_done"] = 10   # Updates an existing key
student["city"] = "Toronto"    # Adds a brand-new key
student.pop("city")            # Removes a key

Safe 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:

python
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:

python
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):

python
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:

  1. Item 1 (Lunch, Food, $12): totals.get("Food", 0) is 0 → 0 + 12 = 12 → totals becomes {"Food": 12}
  2. Item 2 (Bus, Travel, $4): totals.get("Travel", 0) is 0 → 0 + 4 = 4 → totals becomes {"Food": 12, "Travel": 4}
  3. Item 3 (Coffee, Food, $5): totals.get("Food", 0) is 12 → 12 + 5 = 17 → totals becomes {"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

Python 3Try It Live: Expense Category Summary
Output

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

Check Your Understanding

Why is profile.get('phone', 'None') safer than profile['phone']?