Iterating a map with range
- Go course
- Beginner
- Lesson 55/90
- 4 min
Learn to loop over a map with range.
range over a map
for k, v := range m walks every key-value pair in the map. The order is undefined and Go deliberately shuffles it on every run; code must not rely on the order.
notlar := map[string]int{"Ada": 90, "Can": 75}
for ad, not := range notlar {
fmt.Println(ad, not) // order may vary
}If only the keys are needed, write for ad := range notlar.
Ordered iteration
When ordered output is needed, the keys are separated and sorted:
anahtarlar := make([]string, 0, len(notlar))
for ad := range notlar {
anahtarlar = append(anahtarlar, ad)
}
slices.Sort(anahtarlar)
for _, ad := range anahtarlar {
fmt.Println(ad, notlar[ad])
}fmt.Println(m), on the other hand, always prints a map in key order; it is a convenience just for printing.
Practice Sorted grade list
Declare notlar := map[string]int{"Can": 75, "Ada": 90, "Ece": 82}. Collect the keys into a slice, sort them with slices.Sort and print name grade on each line.
Starter code
package main
import (
"fmt"
"slices"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"slices"
)
func main() {
notlar := map[string]int{"Can": 75, "Ada": 90, "Ece": 82}
anahtarlar := make([]string, 0, len(notlar))
for ad := range notlar {
anahtarlar = append(anahtarlar, ad)
}
slices.Sort(anahtarlar)
for _, ad := range anahtarlar {
fmt.Println(ad, notlar[ad])
}
}Expected output
Ada 90 Can 75 Ece 82
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What do you do to print a map sorted by key?
- Collect the keys into a slice, sort it, then iterate the slice Correct answer
- range is already sorted
- Call sort.Map(m)
- It isn't possible
Explanation: With Go 1.21+, slices.Sorted(maps.Keys(m)) does it briefly; in older versions the keys are collected by hand and sorted with sort.Strings.
2 Key and value
for ad, puan := ____ notlar {
fmt.Println(ad, puan)
}
for ad, puan := range notlar {
fmt.Println(ad, puan)
}
Explanation: range gives the map's keys and values in turn.
3 Code and behavior
| Term | Meaning |
|---|---|
for k, v := range m |
Random order |
for k := range m |
Keys only |
slices.Sort(anahtarlar) |
Sorted keys |
fmt.Println(m) |
Prints in key order |