Concepts / List Sorting and Ordering

List Sorting and Ordering

Looping over a dictionary with for key in dict: iterates through the keys; use dict[key] to access the value.

  • Programming

From Key to Value

A dictionary stores entries as key-value pairs. When a for loop iterates directly over a dictionary, the loop variable receives a key. That key can then be used inside square brackets to retrieve the corresponding value. The important sequence is: the loop produces a key, and dict[key] retrieves the value associated with that key.

loop receives a keyused inside lookupretrievesscoresdictionaryAdaloop variable keyscores[key]value lookup91corresponding value
When a loop produces a dictionary key, how does dict[key] lead to the corresponding value?
python
Output
Ada 91
Lin 84
Mina 96

Tracing One Loop

Reading Each Dictionary Entry

Consider the dictionary scores = {"Ada": 91, "Lin": 84, "Mina": 96}. What does the loop use on each pass?

First pass: The loop receives a key from the dictionary. If the key is Ada, scores[key] means scores["Ada"], so the corresponding value is 91.

Second pass: The loop receives another key. If the key is Lin, scores[key] means scores["Lin"], so the corresponding value is 84.

Third pass: The loop receives another key. If the key is Mina, scores[key] means scores["Mina"], so the corresponding value is 96.

Pattern: The loop variable is a key, not a value. The lookup expression uses that key to reach the value.

A direct dictionary loop visits keys, and dict[key] accesses the value paired with the current key.

Filtering by Value

Dictionary iteration can be combined with conditional logic. The loop still receives a key, but the condition examines dict[key], the value associated with that key. Only entries whose values satisfy the condition are printed or otherwise processed.

look up valuetest valueyesnoCurrent keyscores[key]current valuevalue >= 90Print entrycondition trueSkip entrycondition false
How does the loop decide which key-value pairs pass a value-based condition and which are skipped?
python
Output
Ada 91
Mina 96

The condition does not change which object the loop traverses: it still traverses dictionary keys. It changes what happens after each key is received. The current value is looked up, tested, and either allowed through or skipped.

Alphabetical Key Order

A direct loop over a dictionary is not the same as a loop over alphabetically sorted keys. To sort dictionary entries alphabetically by key, first extract the keys with list(dict.keys()), sort that separate list, and then loop through the sorted list. Each sorted key is used to look up its value in the original dictionary.

extract keysextract and sort keysscoresoriginal dictionarykey listoriginal key sequencescoresoriginal dictionarysorted_keysalphabetical key sequence
What changes when dictionary keys are converted into an alphabetically sorted sequence before printing?
python
Output
Ada 91
Lin 84
Mina 96

Two Traversal Strategies

supplies keyslook up each valuesupplies alphabetically sorted keyslook up each valuedictionarykeys supplied directlyfor key in scorescurrent keyscores[key]lookup valuesorted key listalphabetical keysfor key insorted_keyscurrent keyscores[key]lookup value
How does data move differently when looping directly over a dictionary compared with looping over sorted(dict.keys())?
Direct dictionary iterationIteration over sorted keys
The for loop receives keys directly from the dictionary.The for loop receives keys from a separate sorted list.
Use dict[key] to access each corresponding value.Use the sorted key with dict[key] to access each corresponding value.
No separate sorted key list is used.The original dictionary remains unchanged while the separate key list is sorted.

The lookup expression can remain the same in both strategies: dict[key]. The difference is the source of key. In direct iteration, key comes from the dictionary. In sorted iteration, key comes from the separately extracted and sorted list.

Mistakes to Avoid

  • Treating the loop variable as a value during direct dictionary iteration.

    A direct for loop over a dictionary iterates through keys. The loop variable therefore represents a key.

    Fix: Use a key variable and retrieve the value with scores[key].

  • Testing the key instead of the value when filtering.

    The value-based condition must examine the value associated with the current key.

    Fix: Use a condition such as if scores[key] >= 90:.

  • Assuming that sorting a key list sorts the original dictionary.

    The sorting operation applies to the separate list of keys.

    Fix: Continue using scores as the original dictionary and use sorted_keys to control the traversal order.

  • Sorting keys but then printing only the keys.

    This traverses the sorted keys but does not display the corresponding values.

    Fix: Use print(key, scores[key]) when both parts of each entry are needed.

Practice Check

MEDIUM

Write a loop that prints only the entries in the dictionary results = {"Zoe": 88, "Ari": 94, "Bea": 91} whose values are at least 90. Then adapt the solution so the qualifying entries are printed in alphabetical order by key.

Hints
  • In a direct loop, the loop variable is a key.
  • Use results[key] for the value-based condition.
  • For alphabetical output, create a list from results.keys(), sort that list, and loop through it.

What do you think happens?

If the keys are first placed into a separate sorted list, does sorting that list change the original dictionary?

Reveal answer

Answer: No. The original dictionary remains unchanged; only the separate list of keys is sorted.

The sorted list controls the order in which keys are visited. Each key is still used to look up its value in the original dictionary.

Key Takeaways

  1. A for loop over a dictionary iterates through keys.
  2. Use dict[key] to access the value associated with the current key.
  3. A conditional inside the loop can filter entries by value.
  4. Alphabetical ordering requires extracting the keys into a list, sorting that list, and looping through it.
  5. Sorting the separate key list does not change the original dictionary.

Key Takeaways

  • Direct dictionary iteration produces keys, not values.
  • The expression dict[key] retrieves the value for the current key.
  • Conditional logic can select entries according to their values.
  • To print entries alphabetically by key, sort a separate list made from dict.keys().
  • The original dictionary is unchanged when the separate key list is sorted.