Using a For Loop for Dictionaries in Python
Master Python dictionary iteration with practical examples
This tutorial follows a hands-on video transcription format with practical code examples you can follow along with step by step.
Dictionary Iteration Methods Covered
Basic Key Iteration
Learn how for loops naturally iterate through dictionary keys. Perfect for accessing keys directly in your code.
Key-Value Access
Discover how to access both keys and their corresponding values during iteration. Essential for data processing tasks.
Items Method Approach
Master the items() method for unpacking key-value pairs into separate variables. Most Pythonic approach for complex operations.
Basic Dictionary Setup and Key Iteration
Create the Dictionary
Define a menu dictionary with items as keys and prices as values: hamburger (5.75), nachos (9.99), salad (2.75)
Iterate Through Keys
Use 'for k in menu' to loop through dictionary keys. This returns hamburger, nachos, and salad
Access Values with Keys
Fetch values using menu[k] syntax where k represents each key during iteration
Dictionary Iteration Methods Comparison
| Feature | Basic Key Iteration | Items Method |
|---|---|---|
| Syntax | for k in menu: | for key, value in menu.items(): |
| Direct Access | Keys only | Keys and values |
| Value Retrieval | menu[k] required | Automatic unpacking |
| Best For | Simple key operations | Complex key-value operations |
Menu Price Analysis
Creating New Dictionaries from Iterations
Initialize Empty Dictionary
Create an empty 'sale' dictionary to store modified values from the original menu
Apply Price Reduction
Use round(menu[k] * 0.9, 2) to reduce each price by 10% and round to 2 decimal places
Populate New Dictionary
Assign each modified value to the same key in the new dictionary during iteration
Price Comparison: Original vs Sale vs Super Sale
Items Method vs Basic Key Iteration
The items() method returns tuples with exactly two values each. Python allows you to unpack these directly into two variables (key, value) in the for loop declaration.
Dictionary Iteration Best Practices
Makes code more readable and maintainable
Avoids repeated dictionary lookups and improves performance
Ensures proper decimal precision for monetary values
Prevents errors and makes intent clear
Verify that 0.8 multiplication actually reduces by 20%
Key Takeaways