Concepts / Sorting Lists in Python

Sorting Lists in Python

To print dictionary keys in alphabetical order, extract keys using list(dict.keys()), sort the resulting list with sort(), and loop through the sorted list to retrieve and print key-value pairs.

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

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
request keysconvertcreate listcountspear, apple, orangekeys()dict_keys objectlist()conversionkeyspear, apple, orange
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
sort()unchangedkeyspear, apple, orangekeysapple, orange, pearcountspear, apple, orangecountspear, apple, orange
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.

counts = {"pear": 4, "apple": 7, "orange": 2} keys = list(counts.keys()) keys.sort() for key in keys: print(key, counts[key])

Output
apple 7
orange 2
pear 4
lookuplookuplookupapplefirst key7counts[apple]orangesecond key2counts[orange]pearthird key4counts[pear]
How does each sorted key connect to its corresponding value when producing ordered output?
next keynext keyappleretrieve 7orangeretrieve 2pearretrieve 4
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
supplies lookup keyskeysapple, orange, pearcountspear, apple, orange
How can the key list be reordered without changing the dictionary's stored contents or structure?

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

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

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

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

  • Expecting keys.sort() to reorder the dictionary.

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

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

  • Sorting the keys but not iterating through the sorted list.

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

    Fix: 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.

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.