Go: How to Sort the Keys on a Map

I often want the values in a map to be in key order. That means sorting the keys for a map.

aMap := map[string]string{
  "key2":"val2",
  "key1":"val1",
  "key3":"val3",
  "key5":"val5",
  "key0":"val0",
} 

for aKey, aVal := range aMap {
    fmt.Printf ( "%s maped to %v\n", aKey, aVal )
} 

If you run this code (ex02.go in the download) then you will see that it is not sorting the keys.

with both key and value from the range
key2 maped to val2
key1 maped to val1
key3 maped to val3
key5 maped to val5
key0 maped to val0


To sort the keys you can:

keys := make([]string, 0, len(aMap))
for k := range aMap {
    keys = append(keys, k)
}
sort.Strings(keys)


A complete example (ex03.go):

package main

// A map/key demo

import (
	"fmt"
	"sort"
)

func main() {

	aMap := map[string]string{
		"key2": "val2",
		"key1": "val1",
		"key3": "val3",
		"key5": "val5",
		"key0": "val0",
	}

	fmt.Printf("with both key and value from the range (in undefined order)\n")
	for aKey, aVal := range aMap {
		fmt.Printf("%s maped to %v\n", aKey, aVal)
	}

	keys := make([]string, 0, len(aMap))
	for k := range aMap {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	fmt.Printf("\nIn sorted order based on key\n")
	for i := range keys {
		fmt.Printf("%d: %s maped to %v\n", i, keys[i], aMap[keys[i]])
	}

}


Now the output is in key order:

with both key and value from the range (in undefined order)
key2 maped to val2
key1 maped to val1
key3 maped to val3
key5 maped to val5
key0 maped to val0

In sorted order based on key
0: key0 maped to val0
1: key1 maped to val1
2: key2 maped to val2
3: key3 maped to val3
4: key5 maped to val5



•       •       •       •       •       •

Summary: # of Words: 154
Author: Philip J. Schlump
Published On: 2013-12-05

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens