How to Sort Map by Key in Go: Simple Guide with Example
In Go, maps are unordered, so to sort a map by key, you first extract the keys into a slice, then use
sort.Strings (or sort.Ints for int keys) to sort that slice. Finally, iterate over the sorted keys to access map values in order.Syntax
To sort a map by key in Go, follow these steps:
- Extract keys from the map into a slice.
- Use
sort.Strings(keys)orsort.Ints(keys)to sort the keys slice. - Loop over the sorted keys to access map values in sorted order.
go
keys := make([]string, 0, len(myMap)) for k := range myMap { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { fmt.Println(k, myMap[k]) }
Example
This example shows how to sort a map with string keys and print its keys and values in ascending order.
go
package main import ( "fmt" "sort" ) func main() { myMap := map[string]int{ "banana": 3, "apple": 5, "orange": 2, "grape": 4, } // Extract keys keys := make([]string, 0, len(myMap)) for k := range myMap { keys = append(keys, k) } // Sort keys sort.Strings(keys) // Print map in sorted order for _, k := range keys { fmt.Printf("%s: %d\n", k, myMap[k]) } }
Output
apple: 5
banana: 3
grape: 4
orange: 2
Common Pitfalls
Maps in Go do not maintain order, so trying to iterate directly over a map expecting sorted keys will not work.
Also, sorting keys requires creating a separate slice; you cannot sort the map itself.
Remember to use the correct sort function matching your key type, like sort.Strings for strings or sort.Ints for integers.
go
package main import ( "fmt" ) func main() { myMap := map[string]int{"b": 2, "a": 1} // Wrong: iterating map directly (order not guaranteed) for k, v := range myMap { fmt.Println(k, v) } // Right: extract keys and sort // ... (see previous example) }
Output
b 2
a 1
Quick Reference
| Step | Description | Function/Method |
|---|---|---|
| 1 | Extract keys from map | for k := range myMap { keys = append(keys, k) } |
| 2 | Sort keys slice | sort.Strings(keys) or sort.Ints(keys) |
| 3 | Iterate sorted keys | for _, k := range keys { use myMap[k] } |
Key Takeaways
Maps in Go are unordered; sorting requires extracting keys into a slice.
Use sort.Strings or sort.Ints depending on the key type to sort the keys slice.
Iterate over the sorted keys slice to access map values in order.
Direct iteration over a map does not guarantee any order.
Always match the sort function to the key type for correct sorting.