Computer Science · Ch 10 — Tuples and Dictionaries
Traversing a Dictionary
10.10
Traversing a Dictionary
Traversing a dictionary means visiting each of its items one by one — and the tool for that is the for loop. The textbook shows two equivalent methods.
Start with a dictionary of students and their marks:
>>> marks = {'Anita': 95, 'Bala': 89, 'Chetan': 92, 'Divya': 85}
Method 1 — loop over the keys
Looping over a dictionary directly yields its keys; each value is then looked up inside the loop using dict[key]:
>>> for key in marks:
... print(key, ':', marks[key])
Anita : 95
Bala : 89
Chetan : 92
Divya : 85
Method 2 — loop over key-value pairs with items()
The items() method yields each item as a (key, value) pair, which the loop header unpacks into two variables at once — no separate lookup needed:
>>> for key, value in marks.items():
... print(key, ':', value)
Anita : 95
Bala : 89
Chetan : 92
Divya : 85
``` …