capypad
0 day streak
python / beginner
Snippet

Iterating Through Dictionaries

The .items() method allows you to loop through both the keys and the values of a dictionary at the same time using two variables.

snippet.py
python
1
2
3
scores = {"Alice": 10, "Bob": 15}
for name, val in scores.items():
print(name + ": " + str(val))
Breakdown
1
scores = {"Alice": 10, "Bob": 15}
Defines a dictionary mapping names to numeric scores.
2
for name, val in scores.items():
Starts a loop where 'name' gets the key and 'val' gets the value.
3
print(name + ": " + str(val))
Prints each pair; str() converts the number to text for concatenation.