Iteration and Ordering
Handle random map order.
Iteration and Ordering is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Iterating a Map
Use range to loop over a map, getting each key and value.
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
for k, v := range m {
fmt.Println(k, v)
}
}Order Is Random
Map iteration order is not guaranteed. Go deliberately randomizes it. Running the same loop twice may print keys in different orders.
Why Randomized
Go randomizes order on purpose so developers do not accidentally rely on a specific order. Code that depends on map order is a bug waiting to happen.
Keys Only
Omit the value to iterate just the keys.
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2, "c": 3}
for k := range m {
fmt.Println(k)
}
}Collecting Keys
To get a stable result, collect the keys into a slice first.
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2, "c": 3}
keys := []string{}
for k := range m {
keys = append(keys, k)
}
fmt.Println("collected", len(keys), "keys")
}Sort the Keys
Sort the collected keys, then iterate the slice. This gives deterministic, ordered output.
package main
import (
"fmt"
"sort"
)
func main() {
m := map[string]int{"c": 3, "a": 1, "b": 2}
keys := []string{}
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, m[k])
}
}Ordered Output Pattern
The collect-then-sort pattern is the standard way to print a map in a predictable order. Always sort keys when output order matters.
Sorting Integer Keys
The same idea works for numeric keys with sort.Ints.
package main
import (
"fmt"
"sort"
)
func main() {
m := map[int]string{3: "c", 1: "a", 2: "b"}
keys := []int{}
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Println(k, m[k])
}
}Modifying During Iteration
You may delete keys during a range loop safely. But adding keys during iteration has undefined behavior; the new entries may or may not appear.
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2, "c": 3}
for k := range m {
if k == "b" {
delete(m, k)
}
}
fmt.Println(len(m))
}Sorting by Value
To order by value instead of key, collect keys then sort with a comparison that reads the map values.
package main
import (
"fmt"
"sort"
)
func main() {
m := map[string]int{"a": 3, "b": 1, "c": 2}
keys := []string{}
for k := range m {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return m[keys[i]] < m[keys[j]]
})
for _, k := range keys {
fmt.Println(k, m[k])
}
}Never Rely on Order
Key takeaway: never assume map iteration order. If order matters, extract keys to a slice and sort them explicitly.
Quick Check
You need to print a map's entries in alphabetical key order. What is the correct approach?
Recap
Iteration and ordering:
- Map range order is intentionally random
- Collect keys, sort them, then iterate for deterministic output
- Deleting during range is safe; adding is undefined
Frequently asked questions
Is the “Iteration and Ordering” lesson free?
Yes — the full text of “Iteration and Ordering” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Iteration and Ordering”?
Handle random map order. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Iteration and Ordering” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Map Internals
- Checking Existence
- Maps as Sets
- Iteration and Ordering