Video Transcription
Hi, I'm Art, and I teach Python at Noble Desktop. In this tutorial, I'll demonstrate how to efficiently iterate through Python dictionaries using for loops—a fundamental skill for data manipulation and processing in modern applications.
Let's start by creating a practical example. We'll define a variable called 'menu' and assign it a dictionary representing restaurant items with their prices: hamburger at $5.75, nachos at $9.99, and salad at $2.75. This type of key-value structure is ubiquitous in real-world programming, from processing API responses to managing configuration data.
The most straightforward approach to iterate through a dictionary uses a simple for loop: 'for k in menu'. When you print each 'k', you'll see the keys—hamburger, nachos, and salad. This behavior is crucial to understand: by default, iterating over a dictionary returns only the keys, not the values.
To access the corresponding values, you need to use the key as an index into the dictionary. Simply reference 'menu[k]' where 'k' is your key variable, and Python will return the associated value. This pattern forms the foundation of most dictionary processing operations you'll encounter in production code.
Now, let's apply this concept to a practical scenario. We'll create a new dictionary called 'sale' to store discounted prices. Using our iteration pattern, we can populate this dictionary by applying each item from 'menu' as a key in 'sale', while calculating the value as a 10% discount using 'round(menu[k] * 0.9, 2)'. The round function ensures clean currency formatting—essential for financial calculations.
While this method works perfectly, Python offers a more elegant approach through the 'items()' method. When you call 'menu.items()', Python converts the dictionary into a collection of tuples, where each tuple contains a key-value pair. This approach is often more readable and efficient, particularly when processing large datasets.
Since 'items()' returns tuples with exactly two elements, you can leverage Python's tuple unpacking feature. Instead of 'for key in menu.items()', use 'for key, value in menu.items()'. This syntax automatically assigns the first element of each tuple to 'key' and the second to 'value', eliminating the need for dictionary lookups within your loop.
Let's demonstrate this with another example. We'll create a 'super_sale' dictionary with 20% discounts. Using tuple unpacking, the code becomes more concise: 'super_sale[key] = round(value * 0.8, 2)'. Notice how we multiply by 0.8 rather than 0.2—a common source of logic errors in discount calculations. The result: nachos drop from $9.99 to $7.99, reflecting the intended 20% reduction.
This tuple unpacking approach is particularly valuable in modern Python development, where clean, readable code is prioritized. It reduces potential indexing errors and makes your intentions explicit to other developers reviewing your code. Thank you for watching, and be sure to explore my other Python tutorials for more advanced techniques.
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%