Concepts / Dictionary Methods: keys(), values(), items()

Dictionary Methods: keys(), values(), items()

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 Control Dictionary Output

A dictionary can contain the information you need without arranging its keys in the order you want to show or process them. If a report should list entries alphabetically, or if records should be processed in a predictable sequence, you need to control the order explicitly. The dictionary does not automatically sort its keys for you. A useful strategy is to extract the keys, sort the extracted list, and then use that list to control how you retrieve values.

The key idea is to separate the data from the sequence used to visit it. The dictionary continues to provide the values, while a sorted list of keys controls the order in which those values are accessed.

The Three-Step Pipeline

keys()convertrearrangevisit in orderuse each keycountsdictionarylist(counts.keys())extract keyskey liststored ordersort()alphabetical orderfor keysorted sequencecounts[key]retrieve value
How do dictionary keys move into a list, become alphabetically sorted, and then control iteration?

The process has three stages. First, list(counts.keys()) extracts the dictionary's keys and converts them into a list. Second, sort() rearranges that list alphabetically. Third, a loop visits the sorted keys and uses each one as a lookup instruction for the original dictionary. The dictionary supplies the associated value at the moment of lookup.

Tracing the Key List

Alphabetizing Dictionary Entries

A dictionary contains counts under several keys. Produce key-value pairs in alphabetical order by key.

Extract: Use list(counts.keys()) to create a separate list containing the dictionary keys. At this stage, the keys appear in the order in which they were stored, which is not necessarily alphabetical.

Sort: Call sort() on the extracted list. The list itself is rearranged into alphabetical order.

Iterate: Loop through the sorted list. Each key is used with counts[key] to retrieve its associated value from the original dictionary.

Display: Print or otherwise process each key-value pair as the loop visits the keys in their sorted order.

The output order is determined by the sorted key list, while the original dictionary remains available to provide the values.

counts = { "pears": 4, "apples": 7, "oranges": 3 } keys = list(counts.keys()) keys.sort() for key in keys: print(key, counts[key])

Output
apples 7
oranges 3
pears 4

Sorting Without Rebuilding the Dictionary

extractsorted list controls lookupcountsdictionary datacountsdictionary datakeysstored orderkeysalphabetical order
What changes when the extracted key list is sorted, and what remains unchanged in the original dictionary?

Calling sort() changes the extracted list in place. It does not sort or otherwise modify the original dictionary. This distinction matters: the list becomes the control sequence for iteration, while the dictionary remains the data source for lookups.

Sorting keys is a temporary organization step for output or processing. It does not permanently reorganize the dictionary itself.

Following Each Lookup

counts[key]counts[key]counts[key]applessorted key7associated valueorangessorted key3associated valuepearssorted key4associated value
How does each sorted key connect back to its value when producing organized output?

The loop does not need a second sorted structure containing the values. It already has a key from the sorted list. That key is passed to the dictionary expression counts[key], which retrieves the matching value. Therefore, the values appear in the order established by the sorted keys.

This pattern is useful for reports whose entries should appear alphabetically, user-facing output that should remain consistent, and record processing that needs a predictable sequence.

Mistakes with Key Sorting

  • Calling sort() directly on the result of keys().

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

    Fix: Convert the keys to a list first, then sort the list: keys = list(counts.keys()); keys.sort().

  • Assuming that sorting the extracted list sorts the dictionary.

    sort() rearranges the extracted list in place. The original dictionary remains unchanged.

    Fix: Use the sorted list as the iteration sequence and continue using the original dictionary for value lookups.

  • Iterating through the dictionary instead of the sorted key list when ordered output is required.

    The three-step strategy controls output order by iterating through the sorted list of keys.

    Fix: Iterate through the list after extraction and sorting: for key in keys:.

Choosing the Sorting Strategy

The extract-sort-iterate pattern is lightweight and works well for small to medium-sized dictionaries when the required order is alphabetical by key. If the dictionary is very large, or if the requirement is to sort by values rather than keys, the source recommends considering alternative approaches such as using sorted() with a key parameter or converting the data to a list of tuples.

Practice the Pipeline

What do you think happens?

A dictionary has the keys pears, apples, and oranges. After extracting the keys into a list, sorting the list, and iterating through it to retrieve values, what order should the keys appear in?

  • pears, apples, oranges
  • apples, oranges, pears
  • oranges, pears, apples
Reveal answer

Answer: apples, oranges, pears

The extracted list is sorted alphabetically, and the loop follows that sorted list. The original dictionary supplies the values but does not determine the output sequence for this process.

EASY

Describe the three stages you would use to produce alphabetically ordered key-value output from a dictionary. In your explanation, identify which object is changed by sort() and which object supplies the values.

Hints
  • Begin with the keys() method.
  • Remember that the result of keys() must be converted to a list before sorting.
  • Use each sorted key to look up its value in the original dictionary.

Key Takeaways

  1. Use list(dict.keys()) to extract dictionary keys into a sortable list.
  2. Call sort() on the list, not directly on the dict_keys object.
  3. Iterate through the sorted list to control the order of output.
  4. Use each sorted key to retrieve its associated value from the original dictionary.
  5. Sorting the extracted list does not modify the original dictionary.

Key Takeaways

  • The extract-sort-iterate process creates organized, predictable dictionary output.
  • The keys() method returns a dict_keys object, so convert it to a list before using sort().
  • The sorted key list controls iteration order, while the original dictionary supplies the values.
  • Sorting changes only the extracted list; it leaves the original dictionary unchanged.