The sorted() function in Python provdies a flexible way to sort dictionaries. It accepts three parameters: iterable, key, and reverse.
- iterable: The collection to sort, such as
dict.items()ordict.keys(). - key: A function that determines which part of the elements should be used for comparison.
- reverse: Controls sorting order. When set to
True, results are in descending order; otherwise, ascending (default).
Sorting by Key
To sort dictionary keys alphabeticlaly:
data = {'lilee': 25, 'age': 24, 'phone': 12}
result = sorted(data.keys())
print(result)
# Output: ['age', 'lilee', 'phone']
For reverse alphabetical order:
result = sorted(data.keys(), reverse=True)
print(result)
# Output: ['phone', 'lilee', 'age']
Sorting by Value
There are multiple approaches to sort based on dictionary values.
Using Lambda Function
records = {'lilee': 25, 'wangyan': 21, 'liqun': 32, 'age': 19}
# Ascending order
sorted_asc = sorted(records.items(), key=lambda x: x[1])
print(sorted_asc)
# Output: [('age', 19), ('wangyan', 21), ('lilee', 25), ('liqun', 32)]
# Descending order
sorted_desc = sorted(records.items(), key=lambda x: x[1], reverse=True)
print(sorted_desc)
# Output: [('liqun', 32), ('lilee', 25), ('wangyan', 21), ('age', 19)]
Using operator.itemgetter
import operator
sorted_items = sorted(records.items(), key=operator.itemgetter(1))
print(sorted_items)
# Output: [('age', 19), ('wangyan', 21), ('lilee', 25), ('liqun', 32)]
Packing Keys and Values into Tuples
tuples_list = list(zip(records.keys(), records.values()))
sorted_tuples = sorted(tuples_list)
print(sorted_tuples)
# Output: [('age', 19), ('wangyan', 21), ('lilee', 25), ('liqun', 32)]
Extracting Top N Entries
To retrieve the top entries after sorting:
sample_data = {
"item_a": 5,
"item_b": 6,
"item_c": 4,
"item_d": 3,
}
# Sort by value
sorted_dict = dict(sorted(sample_data.items(), key=lambda pair: pair[1]))
print(sorted_dict)
# Extract first two items
limit = 2
counter = 0
for k, v in sorted_dict.items():
if counter >= limit:
break
print(f"{k}: {v}")
counter += 1