Dictionary Methods and Operations
Looping over a dictionary with for key in dict: iterates through the keys; use dict[key] to access the value.
A Key-by-Key Visit
A dictionary stores entries as key-value pairs. When a for loop iterates directly over a dictionary, each loop variable receives a key. To retrieve the value belonging to that key, use dictionary[key]. This creates a two-step process: the loop visits a key, and the dictionary lookup retrieves the matching value.
scores = {
"Ava": 8,
"Ben": 6,
"Cara": 9
}
for name in scores:
print(name, scores[name])- 1The loop begins by taking a key from scores and assigning it to name.
- 2The expression scores[name] looks up the value for that key.
- 3The loop repeats for the remaining keys.
- The dictionary contains names as keys and scores as values.
- The loop variable name receives one key on each iteration.
- scores[name] retrieves the value associated with the current key.
- The print statement displays the key and its corresponding value.
Ava 8
Ben 6
Cara 9Filtering by Value
A loop can inspect every dictionary entry and use a conditional statement to decide which entries should be printed or processed. The key is still the item received by the loop. The value is obtained with dictionary[key], and the condition tests that value. Entries that satisfy the condition continue to the output; entries that do not satisfy it are skipped.
Selecting Scores Above a Threshold
Print only the names whose scores are greater than 7.
- 1Visit a key
The loop receives one name from the scores dictionary.
- 2Retrieve the value
scores[name] gives the score associated with that name.
- 3Test the value
The condition checks whether the score is greater than 7.
- 4Choose the output
Only entries that satisfy the condition are printed.
The loop filters dictionary entries by value rather than printing every entry.
Ava 8
Cara 9Direct and Sorted Iteration
There are two different looping choices. In direct iteration, for key in dictionary visits the dictionary's keys. In sorted iteration, list(dictionary.keys()) creates a separate list of keys, that list is sorted alphabetically, and the loop visits the sorted list. In both cases, dictionary[key] retrieves the value. The difference is the sequence in which keys are visited.
scores = {
"Zoe": 7,
"Ava": 8,
"Mia": 9
}
keys = list(scores.keys())
keys.sort()
for name in keys:
print(name, scores[name])- 1First, the keys are extracted from scores.
- 2Next, the separate keys list is sorted.
- 3Finally, the loop uses each sorted key in scores[name].
- The dictionary remains the source of the values.
list(scores.keys())extracts the dictionary keys into a separate list.keys.sort()sorts that separate list alphabetically.- The loop visits the sorted keys and uses each one to retrieve its value.
Ava 8
Mia 9
Zoe 7Mistakes to Avoid
Common mistake Expecting the loop variable to contain a value
What it looks likefor name in scores: print(name + 1)Why it failsDirect dictionary iteration provides a key to the loop variable, not the corresponding value.
Do this insteadUse scores[name] when the value is needed.
Common mistake Testing the key when the requirement is about the value
What it looks likeif name > 7:Why it failsThe condition is applied to the key instead of the value associated with that key.
Do this insteadTest scores[name], such as if scores[name] > 7.Common mistake Sorting the dictionary when only alphabetical output is required
What it looks likeThe required method is to create a key list, sort that list, and then look up values.
Why it failsThe source describes sorting a separate list of keys; the original dictionary remains unchanged.
Do this insteadUse keys = list(dictionary.keys()), sort keys, and loop through keys.
Common mistake Sorting keys but looking up values from the wrong object
What it looks likefor name in keys: print(name, keys[name])Why it failsThe sorted list contains keys, while the values remain in the dictionary.
Do this insteadUse dictionary[name] for the value lookup.
Practice the Three Patterns
Given a dictionary named temperatures, write a loop that prints every key and its value. Then modify the loop so it prints only entries whose value is greater than 20. Finally, create a separate sorted list of the keys and print every key-value pair in alphabetical key order.
Hints
- Use for key in temperatures for direct iteration.
- Use temperatures[key] to retrieve the value.
- Place the value comparison inside an if statement.
- Use
list(temperatures.keys())and sort the resulting list before the final loop.
What do you think happens?
Before writing the final loop, what should be sorted: the original dictionary or a separate list made from its keys?
Reveal answer
A separate list of the dictionary's keys
The keys are extracted with list(dictionary.keys()), that separate list is sorted, and the sorted keys are used to look up values in the original dictionary.
Working Rule
- 1Direct dictionary iteration visits keys, so use dictionary[key] to retrieve each matching value.
- 2A conditional inside the loop can filter entries by testing dictionary[key].
- 3For alphabetical output, extract the keys into a separate list and sort that list.
- 4After sorting, use each sorted key to look up its value in the original dictionary.
- 5Sorting the separate key list leaves the original dictionary unchanged.
Key Takeaways
- A for loop over a dictionary directly receives keys.
- Use dictionary[key] to access the value paired with the current key.
- Use conditional logic inside the loop to filter entries by value.
- To print entries alphabetically, sort a separate list created from the dictionary's keys.
- The original dictionary remains unchanged when the separate key list is sorted.