Sort a map by key or value

yourbasic.org/golang

This example uses a sorted slice of keys to print a map[string]int in key order.

m := map[string]int{"Alice": 23, "Eve": 2, "Bob": 25} keys := make([]string, 0, len(m)) for k := range m {	keys = append(keys, k) } sort.Strings(keys) for _, k := range keys {	fmt.Println(k, m[k]) } 

Output:

Alice 23 Bob 25 Eve 2 

Also, starting with Go 1.12, the fmt package prints maps in key-sorted order to ease testing.

Further reading

Maps explained [code example]