Sort a map by value

I found this 5 years old answer at Stackoverflow.

Is this still the state-of-the-art, or is there a better (with better I mean an alternative which needs less typing) way of doing this today?

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)
    }
}

Source: sorting - How can I sort a Map[string]int by its values? - Stack Overflow

Hi @guettli,

AFAIK there is no shorter code than that.

What would you want to leave out?

I would like to leave out the struct.

And I found one, it is possible to avoid the struct: sorting - How can I sort a Map[string]int by its values? - Stack Overflow

1 Like

Indeed, this one is about 20% shorter.

Posting the solution from SO here for reference:

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])
    }
}
1 Like