115

Given this code block

map[string]int {"hello":10, "foo":20, "bar":20}

I would like to print out

foo, 20
bar, 20
hello, 10

In the order of highest to lowest

1
  • As you may know, this situation requires an iteration on a map, which is not recommended because of the Big O matter. Commented Mar 28, 2022 at 18:10

6 Answers 6

112

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

3
  • 1
    ... except Less is returning the wrong result. For reverse sort, use >.
    – Fred Foo
    Commented Sep 9, 2013 at 9:59
  • 3
    @larsmans My bad! Thanks for pointing it out. I have instead used sort.Reverse to get the reverse results
    – samol
    Commented Sep 9, 2013 at 10:23
  • 2
    Even better, I didn't even know about sort.Reverse. +1.
    – Fred Foo
    Commented Sep 9, 2013 at 10:50
109

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

9
  • 4
    I don't like how the output isn't the map I began with
    – hendry
    Commented Apr 1, 2019 at 7:07
  • @hendry this answer is specifically in response to the format in the original question. In go1.12 you can just print the map and it'll be sorted, see the issue: github.com/golang/go/issues/21095 Commented Apr 2, 2019 at 14:39
  • 1
    @TommasoBarbugli that's not what I (or a textbook) mean when I say "stable" sorting. But yes sorting the keys alphabetically is possible, but it's not asked for in the question posted here. Commented May 30, 2020 at 20:52
  • 3
    There is also a sort.SliceStable (also added in Go 1.8) that preserves the original order of the equal elements. Commented Sep 12, 2020 at 11:46
  • 1
    SliceStable is a fine function but it won't stabilize the order of a map. The map iteration order is randomized for a reason. If you want the same results every time it's better to use another tie-breaking element (as Tommaso suggests one could use the string itself). Commented Sep 15, 2020 at 16:18
25

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])
    }
}
3
  • 6
    I am hot sure who is downvoting, probably those who don't read comparator function carefully. Also accepted answer does not produce the printout OP asked for but instead introduces new datastructure that has to be maintained in real code. Here is the playground link for my answer play.golang.org/p/Y4lrEm2-hT5 Commented Jul 12, 2020 at 19:44
  • 2
    This should be the accepted answer, simplest solution.
    – Simon
    Commented May 20, 2022 at 9:18
  • 1
    I think this answer is the best, since it does not need a struct.
    – guettli
    Commented Jun 13, 2022 at 5:55
19

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
3
  • 1
    This assumes that the values don't have identities.
    – newacct
    Commented Sep 10, 2013 at 1:44
  • 2
    @newacct: It solves only the OP problem, not the general case ;-)
    – zzzz
    Commented Sep 10, 2013 at 7:38
  • this solution is the one that worked for my case as well, simple to understand.
    – Tommy
    Commented Jul 30, 2019 at 18:46
3

I often need to sort a map[string]int of something I’m counting and have been using the following.

func rankMapStringInt(values map[string]int) []string {
    type kv struct {
        Key   string
        Value int
    }
    var ss []kv
    for k, v := range values {
        ss = append(ss, kv{k, v})
    }
    sort.Slice(ss, func(i, j int) bool {
        return ss[i].Value > ss[j].Value
    })
    ranked := make([]string, len(values))
    for i, kv := range ss {
        ranked[i] = kv.Key
    }
    return ranked
}

Use it to iterate over the keys in order of value

values := map[string]int{"foo": 10, "bar": 20, "baz": 1}

for i, index := range rankMapStringInt(values) {
    fmt.Printf("%3d: %s -> %d", i, index, values[index])
}
1

In my case, I was dealing with a program that I created. In this program, I created a Map just like you, with string and int. Then I discovered like you that Go doesn't really have a built-in way to sort something like this. I read the other answers and didn't really like what I read.

So I tried to think about the problem differently. Go can use sort.Ints with a slice. Also, Go can use sort.Slice with a custom comparator. So instead of creating a Map of string and int, I created a struct of string and int. Then you can sort:

package main

import (
   "fmt"
   "sort"
)

type file struct {
   name string
   size int
}

func main() {
   a := []file{
      {"april.txt", 9}, {"may.txt", 7},
   }
   sort.Slice(a, func (d, e int) bool {
      return a[d].size < a[e].size
   })
   fmt.Println(a)
}

This will not work for everyone, because maybe you will be forced to deal with a map someone else created. But it was useful for me. Good part is, unlike all the other answers, this one uses no loops.

1
  • Your answer answers a slightly different question. Please stick to the input structure (map) of the original question.
    – guettli
    Commented Jun 13, 2022 at 5:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.