How can I sort a Map[string]int by its values?
Solution 1:
Found the answer on Golang-nuts by Andrew Gerrand
You can implement the sort interface by writing the len/less/swap functions
func rankByWordCount(wordFrequencies map[string]int) PairList{
pl := make(PairList, len(wordFrequencies))
i := 0
for k, v := range wordFrequencies {
pl[i] = Pair{k, v}
i++
}
sort.Sort(sort.Reverse(pl))
return pl
}
type Pair struct {
Key string
Value int
}
type PairList []Pair
func (p PairList) Len() int { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
func (p PairList) Swap(i, j int){ p[i], p[j] = p[j], p[i] }
For the original post, please find it here https://groups.google.com/forum/#!topic/golang-nuts/FT7cjmcL7gw
Solution 2:
There's a new sort.Slice function in go 1.8, so now this is simpler.
package main
import (
"fmt"
"sort"
)
func main() {
m := map[string]int{
"something": 10,
"yo": 20,
"blah": 20,
}
type kv struct {
Key string
Value int
}
var ss []kv
for k, v := range m {
ss = append(ss, kv{k, v})
}
sort.Slice(ss, func(i, j int) bool {
return ss[i].Value > ss[j].Value
})
for _, kv := range ss {
fmt.Printf("%s, %d\n", kv.Key, kv.Value)
}
}
https://play.golang.org/p/y1_WBENH4N
Solution 3:
For example:
package main
import (
"fmt"
"sort"
)
func main() {
m := map[string]int{"hello": 10, "foo": 20, "bar": 20}
n := map[int][]string{}
var a []int
for k, v := range m {
n[v] = append(n[v], k)
}
for k := range n {
a = append(a, k)
}
sort.Sort(sort.Reverse(sort.IntSlice(a)))
for _, k := range a {
for _, s := range n[k] {
fmt.Printf("%s, %d\n", s, k)
}
}
}
Playground
Output:
foo, 20
bar, 20
hello, 10
Solution 4:
Sort keys first by value and then iterate map:
package main
import (
"fmt"
"sort"
)
func main() {
counts := map[string]int{"hello": 10, "foo": 20, "bar": 20}
keys := make([]string, 0, len(counts))
for key := range counts {
keys = append(keys, key)
}
sort.Slice(keys, func(i, j int) bool { return counts[keys[i]] > counts[keys[j]] })
for _, key := range keys {
fmt.Printf("%s, %d\n", key, counts[key])
}
}