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.
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
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.
- 1Extract
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. - 2Sort
Call
sort()on the extracted list. The list itself is rearranged into alphabetical order. - 3Iterate
Loop through the sorted list. Each key is used with counts[key] to retrieve its associated value from the original dictionary.
- 4Display
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])- 1The variable counts refers to the original dictionary.
- 2The expression
list(counts.keys())extracts the keys and converts them to a list. - 3The
sort()method changes the order of the keys in that list. - 4The for loop reads one sorted key at a time.
- 5The expression counts[key] looks up the current key in the original dictionary.
- 6The 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.
apples 7
oranges 3
pears 4apples 7
oranges 3
pears 4Sorting Without Rebuilding the 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
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
Common mistake Calling sort() directly on the result of keys().
What it looks likecounts.keys().sort()Why it failsThe
keys()method returns adict_keysobject, anddict_keysobjects do not have asort()method.Do this insteadConvert 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 likekeys = list(counts.keys()); keys.sort()Why it failssort()rearranges the extracted list in place. The original dictionary remains unchanged.Do this insteadUse 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 likefor key in counts:Why it failsThe three-step strategy controls output order by iterating through the sorted list of keys.
Do this insteadIterate 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?
Reveal 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.
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
- 1Use
list(dict.keys())to extract dictionary keys into a sortable list. - 2Call
sort()on the list, not directly on thedict_keysobject. - 3Iterate through the sorted list to control the order of output.
- 4Use each sorted key to retrieve its associated value from the original dictionary.
- 5Sorting 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 adict_keysobject, so convert it to a list before usingsort(). - 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.