Dictionary Methods

Back

Loading concept...

🏠 The Dictionary Toolbox: Mastering Dictionary Methods

Imagine you have a magical address book. You can add new friends, update their phone numbers, remove people who moved away, and even make copies to share. Python dictionaries work exactly like that!


🎯 What You’ll Learn

In this adventure, you’ll master the tools (methods) that let you:

  • Add and update items
  • 🗑️ Remove items safely
  • 📋 Copy dictionaries
  • ⚡ Create dictionaries with comprehensions
  • 🔀 Merge dictionaries together
  • 📦 Work with nested dictionaries

Let’s open our toolbox!


1️⃣ Adding and Updating Items

The Story

Think of your dictionary as a toy box with labeled compartments. Want to add a new toy? Just put it in a compartment and stick a label on it!

Method 1: Square Bracket Assignment

toys = {"car": "red", "ball": "blue"}

# Add a new toy
toys["robot"] = "silver"

# Update existing toy
toys["car"] = "green"

print(toys)
# {'car': 'green', 'ball': 'blue',
#  'robot': 'silver'}

Key insight: Same syntax does TWO jobs—adds if new, updates if exists!

Method 2: The update() Method

When you have MANY items to add at once:

toys = {"car": "red"}

# Add multiple items
toys.update({
    "ball": "blue",
    "kite": "yellow"
})

print(toys)
# {'car': 'red', 'ball': 'blue',
#  'kite': 'yellow'}

You can also use keyword arguments:

toys.update(doll="pink", drum="brown")

Method 3: The setdefault() Method

This is the polite method—it only adds if the key doesn’t exist:

toys = {"car": "red"}

# Won't change existing key
toys.setdefault("car", "blue")
print(toys["car"])  # Still "red"!

# Will add new key
toys.setdefault("plane", "white")
print(toys["plane"])  # "white"

Perfect for: Setting defaults without overwriting!


2️⃣ Removing Dictionary Items

The Story

Sometimes you need to clean out your toy box. Python gives you different tools depending on what you need to do.

Method 1: del Statement

The direct approach—just delete it:

pets = {"dog": "Max", "cat": "Luna",
        "fish": "Bubbles"}

del pets["fish"]
print(pets)
# {'dog': 'Max', 'cat': 'Luna'}

⚠️ Warning: Raises KeyError if key doesn’t exist!

Method 2: pop() Method

Delete AND get the value back:

pets = {"dog": "Max", "cat": "Luna"}

removed = pets.pop("cat")
print(removed)  # "Luna"
print(pets)     # {'dog': 'Max'}

# Safe version with default
gone = pets.pop("bird", "not found")
print(gone)  # "not found"

Method 3: popitem() Method

Remove the LAST item added:

colors = {"a": "red", "b": "blue",
          "c": "green"}

last = colors.popitem()
print(last)    # ('c', 'green')
print(colors)  # {'a': 'red', 'b': 'blue'}

Method 4: clear() Method

The nuclear option—remove EVERYTHING:

stuff = {"a": 1, "b": 2, "c": 3}
stuff.clear()
print(stuff)  # {}
graph TD A["Remove Item?"] --> B{Need the value?} B -->|Yes| C["Use pop"] B -->|No| D{Remove last?} D -->|Yes| E["Use popitem"] D -->|No| F{Remove all?} F -->|Yes| G["Use clear"] F -->|No| H["Use del"]

3️⃣ Copying Dictionaries

The Story

Imagine you want to give your friend a copy of your recipe book. You don’t want them changing YOUR book when they change theirs!

⚠️ The Trap: Assignment Doesn’t Copy!

original = {"a": 1, "b": 2}
not_a_copy = original  # Same book!

not_a_copy["c"] = 3
print(original)  # {'a': 1, 'b': 2, 'c': 3}
# Original changed too! 😱

Method 1: copy() Method (Shallow Copy)

original = {"a": 1, "b": 2}
real_copy = original.copy()

real_copy["c"] = 3
print(original)   # {'a': 1, 'b': 2}
print(real_copy)  # {'a': 1, 'b': 2, 'c': 3}
# Original is safe! ✅

Method 2: dict() Constructor

original = {"a": 1, "b": 2}
another_copy = dict(original)

Deep Copy for Nested Dictionaries

When you have dictionaries INSIDE dictionaries:

import copy

nested = {"level1": {"level2": "deep"}}

shallow = nested.copy()
deep = copy.deepcopy(nested)

# Shallow copy shares inner dict!
shallow["level1"]["level2"] = "changed"
print(nested)  # Changed too! 😱

# Deep copy is fully independent
deep["level1"]["level2"] = "safe"
print(nested)  # Not affected! ✅

4️⃣ Dictionary Comprehensions

The Story

What if you could build a whole toy collection in ONE magical line? That’s dictionary comprehension!

Basic Pattern

# {key: value for item in iterable}

squares = {x: x**2 for x in range(5)}
print(squares)
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

With Conditions

Add only SOME items:

# Only even numbers
evens = {x: x**2 for x in range(10)
         if x % 2 == 0}
print(evens)
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Transform Existing Dictionary

prices = {"apple": 1.0, "banana": 0.5}

# 20% discount on all
sale = {k: v * 0.8 for k, v in
        prices.items()}
print(sale)
# {'apple': 0.8, 'banana': 0.4}

Swap Keys and Values

original = {"a": 1, "b": 2, "c": 3}

flipped = {v: k for k, v in
           original.items()}
print(flipped)
# {1: 'a', 2: 'b', 3: 'c'}

5️⃣ Dictionary Merge Operators

The Story

You and your friend both have candy collections. How do you combine them? Python 3.9+ gives you super easy ways!

The | Operator (Union/Merge)

Creates a NEW dictionary:

candy1 = {"lollipop": 3, "gummy": 5}
candy2 = {"chocolate": 2, "gummy": 10}

combined = candy1 | candy2
print(combined)
# {'lollipop': 3, 'gummy': 10,
#  'chocolate': 2}

Note: Right side wins for duplicates!

The |= Operator (Update In-Place)

Modifies the original:

candy1 = {"lollipop": 3, "gummy": 5}
candy2 = {"chocolate": 2}

candy1 |= candy2
print(candy1)
# {'lollipop': 3, 'gummy': 5,
#  'chocolate': 2}

Compare with update()

# These do the same thing:
dict1.update(dict2)
dict1 |= dict2

# But | creates NEW dict:
new_dict = dict1 | dict2  # Original unchanged
graph TD A["Merge Dictionaries"] --> B{Modify original?} B -->|No| C["Use | operator"] B -->|Yes| D["Use |= or update#40;#41;"] C --> E["Creates new dict"] D --> F["Changes existing dict"]

6️⃣ Nested Dictionaries

The Story

Think of a school with many classrooms. Each classroom has students. Each student has grades. That’s nesting—dictionaries inside dictionaries!

Creating Nested Dictionaries

school = {
    "class_a": {
        "alice": {"math": 95, "english": 88},
        "bob": {"math": 78, "english": 92}
    },
    "class_b": {
        "charlie": {"math": 85, "english": 90}
    }
}

Accessing Nested Values

Chain the keys:

# Get Alice's math grade
grade = school["class_a"]["alice"]["math"]
print(grade)  # 95

Safe Access with get()

# This could crash if keys missing:
# school["class_c"]["dave"]["math"]

# Safe way:
grade = school.get("class_c", {}) \
              .get("dave", {}) \
              .get("math", "N/A")
print(grade)  # "N/A"

Adding to Nested Dictionaries

# Add new student to class_a
school["class_a"]["eve"] = {
    "math": 91,
    "english": 89
}

# Update existing grade
school["class_a"]["alice"]["math"] = 97

Looping Through Nested Dictionaries

for class_name, students in school.items():
    print(f"=== {class_name} ===")
    for student, grades in students.items():
        avg = sum(grades.values()) / len(grades)
        print(f"  {student}: {avg:.1f}")

🎯 Quick Reference

Task Method Returns
Add/Update d[key] = val None
Add many d.update({...}) None
Add if missing d.setdefault(k,v) Value
Remove del d[key] None
Remove & get d.pop(key) Value
Remove last d.popitem() Tuple
Remove all d.clear() None
Copy d.copy() New dict
Deep copy copy.deepcopy(d) New dict
Merge new d1 | d2 New dict
Merge in-place d1 |= d2 None

🏆 You Did It!

You now have a complete dictionary toolbox:

  1. ✅ Add and update items three different ways
  2. ✅ Remove items safely with the right tool
  3. ✅ Copy dictionaries without surprises
  4. ✅ Build dictionaries in one line with comprehensions
  5. ✅ Merge dictionaries with modern operators
  6. ✅ Navigate nested structures like a pro

Next step: Practice these methods until they feel natural. Your Python code will be cleaner and more powerful!

“A dictionary is only as useful as your ability to manage it. Now you can do anything!”

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.