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

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

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.

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

Key point

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

countsdictionarylist(counts.keys())extract keyskey liststored ordersort()alphabetical orderfor keysorted sequencecounts[key]retrieve valuekeys()convertrearrangevisit in orderuse each key
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

Worked example

Alphabetizing Dictionary Entries

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

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

  2. 2
    Sort

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

  3. 3
    Iterate

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

  4. 4
    Display

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

Result

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

Code walkthrough
counts = {
    "pears": 4,
    "apples": 7,
    "oranges": 3
}

keys = list(counts.keys())
keys.sort()

for key in keys:
    print(key, counts[key])
  1. 1
    The variable counts refers to the original dictionary.
  2. 2
    The expression list(counts.keys()) extracts the keys and converts them to a list.
  3. 3
    The sort() method changes the order of the keys in that list.
  4. 4
    The for loop reads one sorted key at a time.
  5. 5
    The expression counts[key] looks up the current key in the original dictionary.
  6. 6
    The print call produces key-value output in the sorted key order.
  • The dictionary stores the key-value data.
  • list(counts.keys()) creates a list of keys.
  • keys.sort() rearranges only the list.
  • The loop visits apples, oranges, and pears in alphabetical order.
  • counts[key] retrieves the value associated with the current key.
Output
apples 7
oranges 3
pears 4
Output
apples 7
oranges 3
pears 4

Sorting Without Rebuilding the Dictionary

countsdictionary datacountsdictionary datakeysstored orderkeysalphabetical orderextractsorted list controls lookup
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.

Key point

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

Following Each Lookup

applessorted key7associated valueorangessorted key3associated valuepearssorted key4associated valuecounts[key]counts[key]counts[key]
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.

In the real world

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

  • Common mistake

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

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

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

    Do this instead

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

  • Common mistake

    Assuming that sorting the extracted list sorts the dictionary.

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

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

    Do this instead

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

  • Common mistake

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

    What it looks like
    for key in counts:
    Why it fails

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

    Do this instead

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

At a glance

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

Related concepts

More concepts starting with D