Lecture
Utilizing for Loops with Dictionaries
Using a for loop with a dictionary allows you to sequentially process the keys and values within the dictionary.
Using For Loops with Dictionaries
When iterating over a dictionary, the items() method allows iteration over both its keys and values.
Next to the for keyword, two variables such as key, value can be used to access the keys and values of the dictionary.
The first variable gets assigned the dictionary's key, while the second receives its value.
Example of Using For Loop with Dictionary
info = {'name': 'CodeBuddy', 'age': 30, 'city': 'New York'} # Iterate over keys and values of the dictionary for key, value in info.items(): # Print each key and value on a separate line print(f"{key}: {value}")
By using a for loop with a dictionary, you can handle the keys and values differently based on certain conditions.
Example of Conditional Handling in For Loop with Dictionary
info = {'name': 'CodeBuddy', 'age': 30, 'city': 'New York'} # Iterate over keys and values of the dictionary for key, value in info.items(): # If the key is 'age', add 10 to the value before printing if key == 'age': print(f"{key}: {value + 10}") else: # Otherwise, print the key and value as is print(f"{key}: {value}")
Previous lessonExpanding Sequence Elements with the Spread OperatorNext lessonHow to Create a Range of Numbers in Python
Lessons in this chapter · For Loop: Structure and Usage
- 1. How to Perform Iterations Based on Conditions in Python
- 2. Using `for` loops with Lists
- 3. Nested Lists and Nested Loops
- 4. Multiple-choice quiz
- 5. Expanding Sequence Elements with the Spread Operator
- 6. Utilizing for Loops with Dictionaries
- 7. How to Create a Range of Numbers in Python
- 8. Coding Quiz - for Loop
- 9. Multiple-choice quiz
- 10. Fill-in-the-blank quiz
Quiz
0 / 1
What method should be used to iterate over keys and values of a dictionary using a for loop?
keys()
values()
items()
get()
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help