Lecture
Iterating Over Key-Value Pairs with the items() Function
The items() function in a dictionary allows you to use a loop to work with both keys and values.
items() returns each item in the dictionary as a tuple of key-value pairs.
Example of items function
info = {'name': 'CodeMaster', 'age': 30} for key, value in info.items(): print(f"{key}: {value}") # Output # name: CodeMaster # age: 30
Processing Key-Value Pairs with a Loop
When used with a for loop, the items() function allows you to perform various operations on each key-value pair in a dictionary.
Below is an example of code that outputs different messages based on the dictionary's keys.
Example of items function with conditional statements
info = {'name': 'CodeMaster', 'age': 30, 'job': 'developer'} for key, value in info.items(): if key == 'name': print(f"{key} is {value}") elif key == 'age': print(f"{key} will be {value + 5} years old in 5 years") else: print(f"{key} is confidential information")
Previous lessonIterating Over Elements of an IterableNext lessonSimplifying Lists with List Comprehensions
Lessons in this chapter · While Loops and List Comprehensions
- 1. How to Execute a Loop While a Given Condition is True
- 2. Controlling Logic Flow Inside Loops
- 3. Using While Loops with Lists
- 4. Multiple-choice quiz
- 5. Calculating Minimum, Maximum, and Sum
- 6. How to Reverse the Order of Objects
- 7. Iterating Over Elements of an Iterable
- 8. Iterating Over Key-Value Pairs with the items() Function
- 9. Simplifying Lists with List Comprehensions
- 10. Using the join() Function to Concatenate Strings
- 11. Differences Between Iterables and Iterators
- 12. Coding Quiz - Determine Odd/Even
- 13. Multiple-choice quiz
- 14. Fill-in-the-blank quiz
Quiz
0 / 1
Does the items() method of a dictionary return key-value pairs as a list?
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help