Learn Without Walls
← Previous Lesson Lesson 2 of 4 Next Lesson →

Lesson 8.2: Dictionary Methods

What You'll Learn

1. Viewing Keys, Values, and Items

Python provides three methods to view the contents of a dictionary:

fruit_prices = {
    "apple": 1.20,
    "banana": 0.50,
    "cherry": 2.00
}

# Get all keys
print(fruit_prices.keys())

# Get all values
print(fruit_prices.values())

# Get all key-value pairs as tuples
print(fruit_prices.items())
dict_keys(['apple', 'banana', 'cherry']) dict_values([1.2, 0.5, 2.0]) dict_items([('apple', 1.2), ('banana', 0.5), ('cherry', 2.0)])
View Objects: The results of keys(), values(), and items() are view objects. They reflect changes made to the dictionary automatically. You can convert them to lists with list().
# Convert to a regular list if needed
key_list = list(fruit_prices.keys())
print(key_list)
['apple', 'banana', 'cherry']

2. Merging with update()

The update() method adds key-value pairs from one dictionary to another. If a key already exists, its value is updated:

settings = {
    "theme": "light",
    "font_size": 14,
    "language": "English"
}

new_settings = {
    "theme": "dark",
    "notifications": True
}

settings.update(new_settings)
print(settings)
{'theme': 'dark', 'font_size': 14, 'language': 'English', 'notifications': True}

Notice that "theme" was updated from "light" to "dark", and "notifications" was added as a new key.

3. Removing with pop() and clear()

scores = {"Alice": 95, "Bob": 87, "Carol": 92}

# pop() removes a key and returns its value
bob_score = scores.pop("Bob")
print(f"Bob's score was: {bob_score}")
print(scores)

# pop() with a default value (no error if key missing)
dave_score = scores.pop("Dave", "Not found")
print(f"Dave's score: {dave_score}")

# clear() removes ALL entries
scores.clear()
print(scores)
Bob's score was: 87 {'Alice': 95, 'Carol': 92} Dave's score: Not found {}

4. Iterating Over Dictionaries

You can loop through dictionaries in several ways:

Loop Over Keys (Default)

ages = {"Alice": 25, "Bob": 30, "Carol": 28}

# Looping over a dict gives you the keys
for name in ages:
    print(name)
Alice Bob Carol

Loop Over Key-Value Pairs with items()

# Most common pattern: loop over items()
for name, age in ages.items():
    print(f"{name} is {age} years old")
Alice is 25 years old Bob is 30 years old Carol is 28 years old

Loop Over Values Only

# Sum all the ages
total = 0
for age in ages.values():
    total += age
print(f"Total of all ages: {total}")
Total of all ages: 83

Practical Example: Word Counter

sentence = "the cat sat on the mat the cat"
word_count = {}

for word in sentence.split():
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1

for word, count in word_count.items():
    print(f"'{word}' appears {count} time(s)")
'the' appears 3 time(s) 'cat' appears 2 time(s) 'sat' appears 1 time(s) 'on' appears 1 time(s) 'mat' appears 1 time(s)

5. Nested Dictionaries

Dictionary values can themselves be dictionaries, creating nested structures perfect for complex data:

students = {
    "alice": {
        "age": 20,
        "major": "Math",
        "gpa": 3.8
    },
    "bob": {
        "age": 22,
        "major": "CS",
        "gpa": 3.5
    }
}

# Access nested values with chained brackets
print(students["alice"]["major"])
print(students["bob"]["gpa"])

# Loop through nested data
for name, info in students.items():
    print(f"{name}: {info['major']} major, GPA: {info['gpa']}")
Math 3.5 alice: Math major, GPA: 3.8 bob: CS major, GPA: 3.5

6. Other Useful Methods

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

# len() returns the number of key-value pairs
print(len(data))

# setdefault() returns value if key exists,
# otherwise inserts key with default and returns it
val = data.setdefault("d", 4)
print(val)
print(data)

# copy() creates a shallow copy
data_copy = data.copy()
print(data_copy)
3 4 {'a': 1, 'b': 2, 'c': 3, 'd': 4} {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Check Your Understanding

Question: What does the following code print?

d = {"x": 10, "y": 20}
d.update({"y": 99, "z": 30})
for k, v in d.items():
    print(f"{k}={v}")

Answer:

x=10
y=99
z=30

update() changed "y" from 20 to 99 and added "z": 30.

Try It Yourself

Create a dictionary of three friends and their favorite colors. Then:

  1. Print all the names (keys)
  2. Print all the colors (values)
  3. Loop through items and print "Name likes Color"
  4. Add a new friend, then remove one with pop()

Key Takeaways

← Previous: Creating Dictionaries Next: Tuples →