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