Skip to main content

Dictionaries Part 2 — CRUD Operations

Building Real Applications with Dictionaries

In Lesson 7, you learned how to create dictionaries and access values safely using .get(). Now we're going deeper: CRUD operations. CRUD stands for Create, Read, Update, Delete—the four fundamental operations you perform on data. You've already done Create and Read. Now you'll master Update and Delete, plus learn how to check what's in a dictionary before you act on it.

This lesson moves you from passive dictionary reading to active dictionary manipulation. By the end, you'll build a working inventory system that adds items, updates quantities, removes sold-out products, and checks stock availability.


Concept 1: Adding Keys — Creating New Entries

In Lesson 7, you created dictionaries with initial key-value pairs. Now let's add new keys after creation.

The syntax is beautifully simple: assignment to a key that doesn't exist yet creates it.

Loading Python environment...

That's it. No special method. Just assign to a new key, and Python creates the entry.

You can also start with a dictionary and expand it:

Loading Python environment...

💬 AI Colearning Prompt

"In Python, why does assigning to a non-existent key create it instead of raising an error like accessing a non-existent key does?"

This explores the design philosophy: adding should be permissive (create if missing), while reading should be defensive (error if missing). Your AI can explain this distinction.


Concept 2: Updating Values — Modifying Existing Entries

Updating uses the exact same syntax as adding. If the key exists, you overwrite the value:

Loading Python environment...

This is intentional: Python doesn't distinguish between "add" and "update" at the syntax level. The same assignment pattern handles both.

Real-world example: An inventory system during a recount:

Loading Python environment...

🎓 Expert Insight

In AI-native development, you're not memorizing "add vs update" methods. Python treats them as one operation: assign to a key. Your job is understanding the business intent: "Am I creating a new entry or modifying an existing one?" The code is the same; the context determines which.


Concept 3: Unique Keys Constraint — Understanding Overwrites

Here's a critical rule: dictionary keys must be unique. If you assign to a key that already exists, the old value is replaced:

Loading Python environment...

This is different from lists, where adding an item appends it (creates a duplicate). Dictionaries enforce uniqueness.

Why does this matter? Suppose you're importing student grades from two different sources:

Loading Python environment...

Without the unique-key constraint, you'd have duplicate entries and confusion. The constraint forces you to think clearly about data ownership.

✨ Teaching Tip

When building dictionaries, ask yourself: "Could I have duplicate keys in my data?" If yes, you have a design problem. Solve it by changing the value type (e.g., store dict[str, list[int]] if one student has multiple grades) or the key (e.g., use dict[tuple[str, str], int] for (student_name, exam_type) pairs).


Concept 4: Deleting Keys with del — Removing Entries

There are multiple ways to delete keys. The simplest is the del statement:

Loading Python environment...

The del statement removes the key and its value. Simple and direct.

But be careful: del raises a KeyError if the key doesn't exist:

Loading Python environment...

This is actually useful behavior—it tells you there's a logic error. But if you want to delete safely (without crashing if the key is missing), that's where pop() comes in.


Concept 5: Deleting Keys with pop() — Safe Removal

The .pop() method deletes a key and returns its value. It's safer than del because you can provide a default:

Loading Python environment...

The key feature: default values. Unlike del, pop() doesn't crash if the key is missing—you can provide a fallback:

Loading Python environment...

Real-world pattern: Tracking what you sold:

Loading Python environment...

🚀 CoLearning Challenge

Ask your AI Co-Teacher:

"Explain the difference between del dict[key] and dict.pop(key, default). Show me scenarios where you'd use each one. What happens if I try to delete a key that doesn't exist with each method?"

Expected Outcome: You'll understand that del is for certainty (you know the key exists), while pop() is for safety (you're not sure if it exists). You'll know when each is appropriate.


Concept 6: Clearing Everything with .clear() — Resetting Dictionaries

Sometimes you want to empty an entire dictionary without deleting the variable:

Loading Python environment...

.clear() is useful for resetting state. For example, clearing a cache or resetting temporary data:

Loading Python environment...


Concept 7: Checking Key Existence — The in Operator

Before accessing or deleting a key, you should check if it exists. Use the in operator:

Loading Python environment...

This is defensive programming: check before you act.

Pattern 1: Safe access with fallback

You already know .get() handles this:

Loading Python environment...

Pattern 2: Safe deletion with check

Loading Python environment...

Or more idiomatically with pop():

Loading Python environment...

Real-world scenario: Restocking logic

Loading Python environment...


Putting It Together: Complete Inventory System

Here's a working example that demonstrates all CRUD operations:

Loading Python environment...

Output:

Initial inventory: {'apples': 50, 'bananas': 30, 'oranges': 20}
Apples in stock: 50
After sales and restocking: {'apples': 45, 'bananas': 40, 'oranges': 20}
After removing oranges: {'apples': 45, 'bananas': 40}
End of day inventory: {}

💬 AI Colearning Prompt

"Walk me through this inventory system. Explain what each CRUD operation does and why it's different. Then, what would happen if I tried to read from an empty dictionary?"

This reinforces understanding of how the four operations work together in a realistic scenario.


Common Patterns and Pitfalls

Pattern 1: Increment/Decrement Values (Counting)

A common inventory or statistics operation:

Loading Python environment...

Or more concisely with .get():

Loading Python environment...

Teaching Tip: The second pattern is more Pythonic. It reads: "Get the current count (or 0 if not found), add 1, and store it back."

Pattern 2: Checking Before Deletion

Always verify existence before using del:

Loading Python environment...

Pitfall 1: Modifying While Iterating

Don't add or remove keys while looping—it can skip items:

Loading Python environment...

🎓 Expert Insight

These patterns show that dictionaries follow consistent, predictable rules once you understand the core concepts. "Increment a count" is always: get-current-or-default, add-one, store-back. "Delete safely" is always: pop-with-default. You're not memorizing methods—you're applying the same logical patterns repeatedly.


Practice Exercises

Exercise 1: Build a Shopping Cart

Create a shopping cart (dictionary) where items are keys and quantities are values. Implement:

  1. Add 3 items to the cart
  2. Update the quantity of one item
  3. Check if an item is in the cart
  4. Remove an item that's sold out
  5. Print the final cart

Loading Python environment...

Expected behavior:

  • Add items: cart["milk"] = 2, cart["bread"] = 1, cart["eggs"] = 12
  • Update: cart["milk"] = 3
  • Check: if "milk" in cart: print("Milk in cart")
  • Delete: del cart["bread"] (after checking it exists)
  • Final cart should have milk (3) and eggs (12)

Exercise 2: Word Frequency Counter

Given a list of words, count how many times each word appears using a dictionary:

Loading Python environment...

Use the pattern: word_counts[word] = word_counts.get(word, 0) + 1


Exercise 3: Safe Deletion with Tracking

Delete items from inventory and track what was removed:

Loading Python environment...

Expected output:

Removed: 30
Removed: 0
Remaining: {'apples': 50, 'oranges': 20}

Try With AI

Master dictionary CRUD operations and safe deletion patterns.

🔍 Explore CRUD Operations:

"Show me the four dict CRUD operations (Create, Read, Update, Delete) with examples. Demonstrate adding keys, accessing values, updating existing keys, and removing keys."

🎯 Practice Safe Deletion:

"Help me understand del dict[key] vs dict.pop(key, default). Show what happens when key doesn't exist with each. Give a real scenario where pop() is safer (inventory management)."

🧪 Test User Settings:

"Debug a user_settings dict: create with theme/notifications/language, update theme to 'dark', add auto_save=True, check if 'email' exists. Show the in operator and final dict state."

🚀 Apply to Inventory System:

"Build inventory management: add_item(), update_quantity(), remove_sold_out(), check_stock(). Explain which CRUD operation each uses. Handle edge cases: buying more than available, duplicate items, missing items."