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")
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.