Concepts / Sorting Lists in Python

Sorting Lists in Python

The sorted list controls the order of access. The original dictionary remains available to provide the values.

  • Programming

Why Output Order Matters

A dictionary can contain the information you need while still presenting that information in an order you do not want. If you need an alphabetical report, consistent user-facing output, or predictable processing order, use a separate list of keys to control the sequence. The essential pattern is extract, sort, and iterate.

Key point

The sorted list controls the order of access. The original dictionary remains available to provide the values.

Extracting Keys into a List

Begin with the dictionary's keys() method. The expression dict.keys() returns a dict_keys object, so convert it with list() before trying to sort it. The resulting list contains the dictionary's keys in the order in which they were stored at that point. That order is not necessarily alphabetical.

python
countspear, apple, orangekeys()dict_keys objectlist()conversionkeyspear, apple, orangerequest keysconvertcreate list
How do the keys move from the dictionary into a separate list that can be sorted?

Reordering the Key List

What do you think happens?

After these statements run, what happens to the list and to the dictionary?

keys = list(counts.keys())
keys.sort()
  • Only the list is reordered

  • Only the dictionary is reordered

  • Both are permanently reordered

Reveal answer
Answer:

Only the list is reordered.

The sort() method rearranges the list in place. The dictionary is not changed; it remains the source used for later value lookups.

python
keyspear, apple, orangekeysapple, orange, pearcountspear, apple, orangecountspear, apple, orangesort()unchanged
What changes when the extracted key list is sorted, and what remains in the original dictionary?

Looking Up Values in Order

Once the key list is sorted, use a for loop to visit each key. For every key, counts[key] looks in the original dictionary and retrieves the associated value. The loop therefore produces key-value output in the order established by the sorted list, while the dictionary itself is only being queried.

Code walkthrough
counts = {"pear": 4, "apple": 7, "orange": 2}
keys = list(counts.keys())
keys.sort()

for key in keys:
    print(key, counts[key])
  1. 1
    The dictionary contains the key-value pairs.
  2. 2
    The separate keys list becomes the sequence that controls output.
  3. 3
    sort() changes the order of the keys list, not the dictionary.
  4. 4
    The loop begins with the alphabetically first key and continues through the list.
  5. 5
    counts[key] retrieves the value associated with the current key.
  • Create the dictionary that supplies the values.
  • Extract the dictionary keys into a list.
  • Rearrange the list alphabetically in place.
  • Visit each key in the sorted list.
  • Use the current key to retrieve its value from counts.
Output
apple 7
orange 2
pear 4
applefirst key7counts[apple]orangesecond key2counts[orange]pearthird key4counts[pear]lookuplookuplookup
How does each sorted key connect to its corresponding value when producing ordered output?
appleretrieve 7orangeretrieve 2pearretrieve 4next keynext key
What happens on each loop iteration as the program moves through the keys alphabetically?

Keeping the Dictionary Untouched

ObjectRoleChanged by keys.sort()?
keysControls the order in which the loop visits entriesYes
countsProvides the values during each lookupNo

The extracted list and the original dictionary have different roles in the process.

keysapple, orange, pearcountspear, apple, orangesupplies lookup keys
How can the key list be reordered without changing the dictionary's stored contents or structure?
Best practice

Treat the sorted list as a control sequence rather than as a replacement for the dictionary. The list determines when each key is used; the dictionary remains the place from which the associated value is retrieved.

Mistakes to Avoid

  • Common mistake

    Calling sort() directly on dict.keys().

    What it looks like
    counts.keys().sort()
    Why it fails

    keys() returns a dict_keys object, and dict_keys objects do not have a sort() method.

    Do this instead

    Convert the keys first: keys = list(counts.keys()), then call keys.sort().

  • Common mistake

    Expecting keys.sort() to reorder the dictionary.

    What it looks like
    keys = list(counts.keys())
    keys.sort()
    Why it fails

    sort() changes the separate list in place. The original dictionary remains unchanged.

    Do this instead

    Use the sorted list in the loop when you need alphabetical output.

  • Common mistake

    Sorting the keys but not iterating through the sorted list.

    What it looks like
    keys = list(counts.keys())
    keys.sort()
    for key in counts:
        print(key, counts[key])
    Why it fails

    The loop must use the sorted list for the sorted sequence to control output order.

    Do this instead

    Iterate with for key in keys: and use counts[key] for the lookup.

Practice the Three Steps

EASY

Write the three-step pattern for a dictionary named prices. Your solution should extract its keys into a list, sort that list alphabetically, and loop through the sorted keys to display each key with prices[key].

Hints
  • Start with list(prices.keys()).
  • Call sort() on the resulting list.
  • Use the sorted list as the sequence in the for loop.
Key point

Check your solution in order: extract the keys, sort the list, then use each sorted key to look up a value in the original dictionary.

Key Takeaways

  • Use list(dict.keys()) to turn the dictionary keys into a sortable list.
  • Call sort() on that list to arrange the keys alphabetically in place.
  • Iterate through the sorted list to control the order of output.
  • Use dictionary[key] during each iteration to retrieve the associated value.
  • Sorting the extracted list does not modify the original dictionary.

Related concepts

More concepts starting with S