Dictionary Methods and Iteration
Overview
Dive deeper into useful dictionary operations that make data manipulation more powerful. You'll practice looping through keys, values, and items, and explore methods like get(), pop(), and update() for efficient data handling in real-world scenarios.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Dictionary methods: Learn useful methods like
get(),pop(), andupdate(). - Iterating through dictionaries: Discover how to loop through keys, values, and items.
- Checking for keys: Learn how to safely check if a key exists.
- Combining dictionaries: Understand how to merge dictionaries together.
Why This Matters
Dictionary methods make working with dictionaries much easier and safer. Instead of always using square brackets (which can cause errors if a key doesn't exist), methods like get() provide safe alternatives. Iterating through dictionaries lets you process all the data efficiently, which is essential for real-world programming!
Step 1: The get() Method
The get() method safely retrieves a value from a dictionary, returning None (or a default value) if the key doesn't exist:
student = {"name": "Alice", "age": 20}
# Safe access with get()
name = student.get("name") # Returns "Alice"
city = student.get("city") # Returns None (key doesn't exist)
# With default value
city = student.get("city", "Unknown") # Returns "Unknown"
Safer Than Brackets
Using dictionary["key"] raises a KeyError if the key doesn't exist. The get() method returns None instead, preventing crashes!
Default Value
You can provide a default value as the second argument: get("key", "default"). If the key doesn't exist, it returns the default value instead of None.
When to Use
Use get() when you're not sure if a key exists, especially when reading user input or data from external sources.
Key Concept: The get() method is safer than using square brackets because it never raises an error if the key doesn't exist. It's perfect for cases where you're not certain a key exists in the dictionary!
Mini Practice #1: Using get() Method
Try It YourselfTry using the get() method:
What happened? The get() method safely retrieved values. Even though "email" doesn't exist in the dictionary, the code didn't crash - it returned the default value "No email" instead. This is much safer than using person["email"], which would raise a KeyError!
Step 2: The pop() Method
The pop() method removes and returns a value from a dictionary:
student = {"name": "Alice", "age": 20, "grade": "A"}
# Remove and get value
age = student.pop("age") # Removes "age" and returns 20
print(age) # Output: 20
print(student) # Output: {'name': 'Alice', 'grade': 'A'}
How It Works
The pop() method does two things: it removes the key-value pair from the dictionary AND returns the value. This is useful when you need to remove an item and also use its value. Like get(), you can provide a default value if the key doesn't exist!
Step 3: The update() Method
The update() method adds or updates multiple key-value pairs at once:
student = {"name": "Alice", "age": 20}
# Add or update multiple items
student.update({"grade": "A", "city": "Boston"})
print(student) # Output: {'name': 'Alice', 'age': 20, 'grade': 'A', 'city': 'Boston'}
Remember: update() modifies the dictionary in place. If a key already exists, its value is updated. If a key doesn't exist, it's added. This is more efficient than adding multiple items one at a time!
Step 4: Iterating Through Dictionaries
You can loop through dictionaries in several ways: keys, values, or both:
student = {"name": "Alice", "age": 20, "grade": "A"}
# Loop through keys
for key in student:
print(key) # Output: name, age, grade
# Loop through keys explicitly
for key in student.keys():
print(key)
# Loop through values
for value in student.values():
print(value) # Output: Alice, 20, A
# Loop through items (key-value pairs)
for key, value in student.items():
print(f"{key}: {value}")
Keys
Looping through a dictionary directly gives you the keys. You can use keys() method for clarity, though it's optional.
Values
Use values() to loop through just the values. This is useful when you only need the data, not the keys.
Items
Use items() to loop through both keys and values at once. This gives you tuples of (key, value) pairs!
Mini Practice #2: Iterating Through Dictionaries
Try It YourselfTry iterating through a dictionary:
What happened? You used items() to loop through both keys and values at once. The loop gives you each key-value pair, which you can unpack into two variables (fruit and price). This is the most efficient way to process all the data in a dictionary!
Step 5: Checking for Keys
Use the in keyword to check if a key exists in a dictionary:
student = {"name": "Alice", "age": 20}
# Check if key exists
if "name" in student:
print("Name exists!")
if "city" not in student:
print("City does not exist")
Remember: The in keyword checks for keys, not values. Use "key" in dictionary to check if a key exists before accessing it!
End-of-Lesson Exercises
Exercise 1: Use Dictionary Methods
Create a dictionary called inventory with "apples": 10, "bananas": 5, "oranges": 8. Use get() to safely get the value for "apples" and "grapes" (with default 0). Print both values.
Use get() method with and without a default value.
Exercise 2: Iterate Through Dictionary
Create a dictionary called scores with "Alice": 85, "Bob": 92, "Charlie": 78. Use a loop with items() to print each person's name and score in the format "Name: Score".
Use for key, value in dictionary.items() to iterate.