Lesson 7 of 20 · Part 2: Working with data
Maps
Learn Go maps for beginners. Create maps, add, read and delete keys, check whether a key exists with comma ok, loop in sorted order and count words.
4 min read · Updated · Beginner friendly
What you'll learn
- Create a map and add, read, update and delete entries
- Check whether a key exists with the "comma ok" idiom
- Loop over a map, and in a predictable order
- Avoid the nil-map panic
A slice finds a value by its position: “give me element 3”. Often you want to find a value by a name instead: the price of “coffee”, the phone number of “Ada”, the number of times the word “go” appears. That’s what a map is for. It stores key/value pairs and finds a value by its key very quickly.
Other languages call this a dictionary, hash map or associative array.
Creating a map
The type map[string]int means “a map with string keys and int values”:
package main
import "fmt"
func main() {
prices := map[string]float64{
"coffee": 3.50,
"tea": 2.75,
"sandwich": 6.00,
}
fmt.Println(prices["coffee"])
fmt.Println("items on the menu:", len(prices))
}3.5
items on the menu: 3Every line in a map literal ends with a comma, even the last one. Go requires it so that adding a new line later only changes one line.
You can also start with an empty map using make and fill it in:
package main
import "fmt"
func main() {
ages := make(map[string]int)
ages["Ada"] = 36
ages["Linus"] = 21
ages["Ada"] = 37 // assigning to an existing key replaces the value
fmt.Println(ages)
fmt.Println(len(ages))
}map[Ada:37 Linus:21]
2fmt.Println prints map keys in sorted order to make output easier to read. Don’t confuse that with the order of a loop, which is random (see below).
Reading a key that doesn’t exist
Looking up a missing key is not an error. You simply get the zero value of the value type:
package main
import "fmt"
func main() {
stock := map[string]int{"apples": 5, "pears": 0}
fmt.Println(stock["apples"])
fmt.Println(stock["pears"])
fmt.Println(stock["mangoes"]) // not in the map
}5
0
0That’s convenient, but it creates a puzzle: pears and mangoes both print 0. How do you know whether a key is really there?
The “comma ok” idiom
A map lookup can return a second value, a bool that tells you whether the key was found. By convention it’s called ok:
package main
import "fmt"
func main() {
stock := map[string]int{"apples": 5, "pears": 0}
for _, fruit := range []string{"apples", "pears", "mangoes"} {
if count, ok := stock[fruit]; ok {
fmt.Printf("%s: %d in stock\n", fruit, count)
} else {
fmt.Printf("%s: we don't sell these\n", fruit)
}
}
}apples: 5 in stock
pears: 0 in stock
mangoes: we don't sell theseThis value, ok := m[key] pattern appears everywhere in Go. You will see the same “comma ok” shape again with type assertions and channels.
Deleting entries
Use the built-in delete function. Deleting a key that isn’t there is fine; nothing happens.
package main
import "fmt"
func main() {
sessions := map[string]string{"u1": "Ada", "u2": "Grace", "u3": "Linus"}
delete(sessions, "u2")
delete(sessions, "u99") // no error
fmt.Println(sessions, len(sessions))
clear(sessions) // remove everything
fmt.Println(sessions, len(sessions))
}map[u1:Ada u3:Linus] 2
map[] 0Looping over a map
for key, value := range m visits every entry. But the order is not fixed: Go deliberately randomises it, so your program can’t accidentally depend on it.
When you need a predictable order, collect the keys, sort them, and then loop over the sorted keys:
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
distance := map[string]int{ // kilometres from Earth to the Moon, Sun and Mars (rounded)
"Moon": 384_400,
"Sun": 149_600_000,
"Mars": 225_000_000,
}
// Keys in alphabetical order
for _, name := range slices.Sorted(maps.Keys(distance)) {
fmt.Printf("%-5s %d km\n", name, distance[name])
}
}Mars 225000000 km
Moon 384400 km
Sun 149600000 kmmaps.Keys gives you the keys of a map, and slices.Sorted collects them into a sorted slice. Underscores in a number like 384_400 are just for readability and are ignored by Go.
Counting with a map
Because a missing key gives you 0, maps are perfect for counting. counts[word]++ works even the first time a word is seen:
package main
import (
"fmt"
"strings"
)
func main() {
text := "the quick brown fox jumps over the lazy dog the end"
counts := make(map[string]int)
for _, word := range strings.Fields(text) {
counts[word]++
}
fmt.Println("the:", counts["the"])
fmt.Println("fox:", counts["fox"])
fmt.Println("cat:", counts["cat"])
fmt.Println("different words:", len(counts))
}the: 3
fox: 1
cat: 0
different words: 9strings.Fields splits text on any whitespace. You will build on this word counter in the final project.
Maps of slices and other values
Values can be of any type, including slices or other maps. Here each team has a list of members:
package main
import "fmt"
func main() {
teams := map[string][]string{}
teams["backend"] = append(teams["backend"], "Ada")
teams["backend"] = append(teams["backend"], "Linus")
teams["frontend"] = append(teams["frontend"], "Grace")
fmt.Println(teams["backend"])
fmt.Println(len(teams["frontend"]), len(teams["design"]))
}[Ada Linus]
1 0Appending to teams["backend"] works the first time too, because the missing key gives a nil slice and append handles nil slices.
What can be a key?
Keys must be comparable with ==: strings, numbers, booleans, arrays and structs made of comparable fields all work. Slices, maps and functions can’t be keys.
Maps are shared, not copied
Assigning a map to another variable, or passing it to a function, does not copy it. Both names refer to the same map:
package main
import (
"fmt"
"maps"
)
func main() {
a := map[string]int{"x": 1}
b := a // same map
b["y"] = 2
fmt.Println(a)
c := maps.Clone(a) // a real, independent copy
c["z"] = 3
fmt.Println(a, c)
}map[x:1 y:2]
map[x:1 y:2] map[x:1 y:2 z:3]Common mistakes
Writing to a nil map. A map declared with var m map[string]int is nil. Reading from it is fine, but writing to it crashes the program:
package main
func main() {
var scores map[string]int
scores["Ada"] = 10 // panic: assignment to entry in nil map
}Always create the map first with make(map[string]int) or a literal map[string]int{}.
Depending on loop order. If your output order changes between runs, you are ranging over a map. Sort the keys first.
Confusing “missing” with “zero”. If 0 (or "") is a valid value, use the comma ok idiom to tell the difference.
Exercises
1. Phone book. Create a map from names to phone numbers with three entries. Look up one name that exists and one that doesn’t, and print a friendly message for each.
Show solution
package main
import "fmt"
func main() {
phone := map[string]string{
"Ada": "555-0101",
"Grace": "555-0102",
"Linus": "555-0103",
}
for _, name := range []string{"Grace", "Ken"} {
if number, ok := phone[name]; ok {
fmt.Println(name, "->", number)
} else {
fmt.Println(name, "is not in the phone book")
}
}
}Grace -> 555-0102
Ken is not in the phone book2. Letter frequency. Count how often each letter appears in "mississippi" and print the counts in alphabetical order.
Show solution
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
counts := map[rune]int{}
for _, r := range "mississippi" {
counts[r]++
}
for _, r := range slices.Sorted(maps.Keys(counts)) {
fmt.Printf("%c: %d\n", r, counts[r])
}
}i: 4
m: 1
p: 2
s: 43. Group by first letter. Given []string{"apple", "avocado", "banana", "blueberry", "cherry"}, build a map[string][]string that groups the words by their first letter, then print each group in alphabetical order of the letter.
Show solution
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
words := []string{"apple", "avocado", "banana", "blueberry", "cherry"}
groups := map[string][]string{}
for _, w := range words {
first := w[:1]
groups[first] = append(groups[first], w)
}
for _, letter := range slices.Sorted(maps.Keys(groups)) {
fmt.Println(letter, groups[letter])
}
}a [apple avocado]
b [banana blueberry]
c [cherry]Recap
- A map stores key/value pairs:
map[KeyType]ValueType. - Missing keys return the zero value; use
value, ok := m[key]to check for presence. deleteremoves one key,clearremoves all,lencounts entries.- Loop order is random; sort the keys with
slices.Sorted(maps.Keys(m))when order matters. - Never write to a nil map, and remember maps are shared, not copied.
Next, you will create your own types with structs.
Finished this lesson?
Your progress is saved in this browser only.