Iterating Over Maps
Part of the Fundamentals section of Coddy's GO journey — lesson 92 of 109.
The range keyword lets you iterate over all key-value pairs in a map. It returns both the key and value for each entry.
Create a map of fruit inventory:
inventory := map[string]int{
"apples": 5,
"bananas": 8,
"oranges": 12,
}
for fruit, quantity := range inventory {
fmt.Printf("%s: %d\n", fruit, quantity)
}The result shows each key-value pair:
apples: 5
bananas: 8
oranges: 12If you only need the keys, you can omit the second variable:
for fruit := range inventory {
fmt.Println(fruit)
}Challenge
BeginnerIn this challenge, you'll practice iterating over a map using the range keyword in Go. A map of student grades has been created for you. Your task is to iterate through the map and print each student's name and their grade.
Complete the code to iterate through the studentGrades map and print each student's name and grade in the format: Student: [name], Grade: [grade]
Cheat sheet
Use range to iterate over key-value pairs in a map:
inventory := map[string]int{
"apples": 5,
"bananas": 8,
"oranges": 12,
}
for fruit, quantity := range inventory {
fmt.Printf("%s: %d\n", fruit, quantity)
}To iterate over keys only, omit the second variable:
for fruit := range inventory {
fmt.Println(fruit)
}Try it yourself
package main
import (
"fmt"
"sort"
)
func main() {
// A map of student grades
studentGrades := map[string]string{
"Alice": "A",
"Bob": "B",
"Charlie": "B+",
"David": "A-",
"Eva": "C",
}
// Collect the student names (keys) into a slice to sort them
var names []string
for name := range studentGrades {
names = append(names, name)
}
sort.Strings(names)
// TODO: Iterate through the sorted list of student names
// and print each student's name and grade in the format:
// "Student: [name], Grade: [grade]"
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions