Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Traversing a Dictionary
Traversing a Dictionary
Traversing a dictionary means visiting every item it holds — each key together with its value — one at a time, usually to display them or to process them in some way. Since a dictionary is a collection of key-value pairs, a for loop is the natural tool for the job, exactly as it is for stepping through the elements of a list. The difference lies in what the loop hands you on each pass: with a dictionary, the loop works through the keys, and the values are reached through those keys.
The examples below use this dictionary of students and their marks:
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
There are two standard ways to traverse it.
Method 1 — loop over the dictionary itself
When a dictionary is placed directly after in in a for statement, the loop variable takes each key of the dictionary in turn. The value paired with that key is then fetched by indexing the dictionary with the key, using the familiar dict1[key] form:
>>> for key in dict1:
print(key, ':', dict1[key])
Mohan : 95
Ram : 89
Suhel : 92
Sangeeta : 85
On the first pass key holds 'Mohan', so dict1[key] gives 95; on the next pass key holds 'Ram', giving 89; and so on until every pair has been printed. The essential idea is that iterating over a dictionary yields keys only — the value must be looked up explicitly inside the loop body.
Method 2 — loop over the pairs using items()
The dictionary method items() supplies each item as a complete key-value pair. The for loop can therefore use two loop variables at once — the first receives the key and the second receives the value — so no separate lookup is needed inside the loop:
>>> for key, value in dict1.items():
print(key, ':', value)
Mohan : 95
Ram : 89
Suhel : 92
Sangeeta : 85
Here each pair such as ('Mohan', 95) is unpacked automatically: key gets 'Mohan' and value gets 95, and the two are printed directly.
Comparing the two methods
- Both methods visit every item and produce exactly the same output.
- Method 1 iterates over keys and retrieves each value with
dict1[key]— one loop variable, plus an indexing step in the body. - Method 2 iterates over the pairs returned by
items()— two loop variables, with the key and the value both available immediately. …