Concepts / List Sorting and Ordering

List Sorting and Ordering

Sorting changes the separate list of keys, not the original dictionary.

  • 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.

scoresdictionaryAdaloop variable keyscores[key]value lookup91corresponding valueloop receives a keyused inside lookupretrieves
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

Worked example

Reading Each Dictionary Entry

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

  1. 1
    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.

  2. 2
    Second pass

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

  3. 3
    Third pass

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

  4. 4
    Pattern

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

Result

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.

Current keyscores[key]current valuevalue >= 90Print entrycondition trueSkip entrycondition falselook up valuetest valueyesno
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.

scoresoriginal dictionarykey listoriginal key sequencescoresoriginal dictionarysorted_keysalphabetical key sequenceextract keysextract and sort keys
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

dictionarykeys supplied directlyfor key in scorescurrent keyscores[key]lookup valuesorted key listalphabetical keysfor key insorted_keyscurrent keyscores[key]lookup valuesupplies keyslook up each valuesupplies alphabetically sorted keyslook up each 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.

Both strategies use keys to retrieve values; they differ in where the loop gets those keys.

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

  • Common mistake

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

    What it looks like
    for value in scores: print(value)
    Why it fails

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

    Do this instead

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

  • Common mistake

    Testing the key instead of the value when filtering.

    What it looks like
    if key >= 90:
    Why it fails

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

    Do this instead
    Use a condition such as if scores[key] >= 90:.
  • Common mistake

    Assuming that sorting a key list sorts the original dictionary.

    What it looks like
    sorted_keys = list(scores.keys()); sorted_keys.sort()
    Why it fails

    The sorting operation applies to the separate list of keys.

    Do this instead

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

  • Common mistake

    Sorting keys but then printing only the keys.

    What it looks like
    for key in sorted_keys: print(key)
    Why it fails

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

    Do this instead

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

At a glance

  • 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.

Related concepts

More concepts starting with L