Sorted by sort.Slice
If the version of Go is later than 1.7, we can use the sort.Slice
function to quickly sort a dictionary by key or value.
Here is an example:
package main
import (
"fmt"
"sort"
)
func main() {
m1 := map[int]int{
21: 99,
12: 98,
35: 17,
24: 36,
}
// Define a structure for sorting function values later
type kv struct {
Key int
Value int
}
// Initialize the slice of structures
var s1 []kv
// Add the contents of the dictionary to the slice of structures
for i, j := range m1 {
s1 = append(s1, kv{i, j})
}
// Sort the slice based on key by comparing values
sort.Slice(s1, func(i, j int) bool {
// Return true when the key value of the i-th slice is larger than that of the j-th slice
return s1[i].Key < s1[j].Key
})
fmt.Println("Sorted in ascending order by key:")
for _, j := range s1 {
fmt.Printf("%d, %d\n", j.Key, j.Value)
}
}
The output is as follows:
Sorted in ascending order by key:
12, 98
21, 99
24, 36
35, 17
In this program, we used a structure, which we will explain in detail in the later experiments of this chapter.
For now, all you need to know is that a structure is used to store multiple variables of different types. In this program, the kv
structure has two integer variables Key
and Value
.
Then we stored the values of the dictionary in a slice of structures and sorted the slice using the sort.Slice()
function and an anonymous function.
The anonymous function Compare() compares the values of the keys in the structure. If the key value of slice i is greater than that of slice j, it will return true. Thus, the slice of structures is sorted in ascending order based on the key.
We can also use sort.Slice
to sort the dictionary in descending order based on the key or in ascending order based on the value. Let's do a little test: