Lesson 29 of 55
9 mins readPython Sorting Hashes by Values & Keys
In Plain English
Because hashes are inherently unordered, sorting is performed by ordering the list of `keys %hash` based on their values: `sort { $hash{$b} <=> $hash{$a} } keys %hash`.
Deep Dive: How It Works
Sort by Key: `sort keys %hash` (alphabetical by key name).
Sort by Value Ascending: `sort { $hash{$a} <=> $hash{$b} } keys %hash`.
Sort by Value Descending: `sort { $hash{$b} <=> $hash{$a} } keys %hash`.
Secondary Sort: `sort { $hash{$b} <=> $hash{$a} || $a cmp $b } keys %hash`.
Core Rules to Remember

Sort Keys via Lookups: Sort the list of keys using `$hash{$a}` and `$hash{$b}` in the sort block.

Rankings & Leaderboards: Standard Perl idiom for top-N analysis.
Live Interactive Example
Hit Run Code to see it liveLeaderboard: Sorting Hashes by Value
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Output Console
Click "Run Code" to view the rendered output.
How it works: Alice and Dave tied with 96 and were tie-broken alphabetically.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Find Top Metric
Declare `%latency = ( db => 12, api => 45, cache => 3 );`
Sort keys ascending by latency: `sort { $latency{$a} <=> $latency{$b} } keys %latency`.
Print `"Fastest: $sorted[0] ($latency{$sorted[0]}ms)\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.