Skip to content

Count by Title

The Course
•
18 min study

A slice answers "what is at position 2?". Often the question is different: "how many minutes have I spent on Poems?". Searching a slice for the right title every time is slow and easy to get wrong. A map answers that kind of question directly. A map stores values under keys. make(map[string]int) creates an empty map you can write to. Reading a missing key gives the zero value, here 0, so += works on a key the first time. A second result, often named found or ok, says whether the key was really there. Ranging over a map visits the keys in no fixed order.

Predict and run

What does totals["Poems"] hold before the first +=?

Predict, then run Go
package main

import (
	"fmt"
)

func main() {
	totals := make(map[string]int)
	totals["Poems"] += 10
	totals["Poems"] += 15
	minutes, found := totals["Essays"]
	fmt.Println(totals["Poems"], minutes, found)
}
Check your prediction
Text
25 0 false

Add totals["Essays"] = 0 before the lookup. The value stays 0, but what happens to found?

Reading the map type

map[string]int means "a map from string keys to int values". Each key appears at most once, and each key has exactly one value. Writing to a key that already exists replaces its value; writing to a new key adds it. len(totals) gives the number of keys, and delete(totals, "Poems") removes one.

Write, replace and delete Go
package main

import (
	"fmt"
)

func main() {
	goals := map[string]int{"Poems": 20, "Essays": 30}
	goals["Essays"] = 45
	goals["Letters"] = 10
	fmt.Println(len(goals), goals["Essays"])
	delete(goals, "Poems")
	fmt.Println(goals)
}
Text
3 45
map[Essays:45 Letters:10]

A map literal such as map[string]int{"Poems": 20} creates a map that already has some keys. fmt.Println prints a map with its keys sorted, which makes it handy for checking contents.

Zero values and the comma-ok form

Reading a key that is not in the map is not an error. You get the value type's zero value, so a count or a total can start from nothing with += and no setup. That convenience has a cost: a stored 0 and a missing key look the same. When the difference matters, ask for the second result. minutes, found := totals["Essays"] sets found to true only when the key is present. Go programmers often call this the comma-ok form and name the variable ok.

Make a map before writing to it

var totals map[string]int declares a map whose zero value is nil. Reading from a nil map is fine and returns zero values, but writing to it stops the program with assignment to entry in nil map. Create a writable map with make or with a literal, even an empty one such as map[string]int{}.

Map order is not fixed

A range loop over a map visits every key, but Go deliberately changes the order from run to run. Code that depends on map order may pass today and fail tomorrow. When output must appear in a fixed order, keep the keys you want in a slice and look each one up, as the checkpoint does. Sorting the keys is another option you will meet in the intermediate course.

When to use a map and when to use a slice

Use a slice when order matters or when you will visit every item, such as a list of sessions in the order they happened. Use a map when you look things up by a name or an ID, or when you need to combine records that share a key, such as total minutes per title. Many programs use both: a slice of records as input and a map of totals as the summary.

Practice

Exercise

Your turn

The starter has the titles from five sessions. Count how many times each title appears in a map, then print the count for Poems. Use the comma-ok form to report that Novels was never logged. Finally delete Plays and print how many titles are left. The output should be:

Text
Poems: 3
Novels: not logged
Titles: 2
Your working space Go
package main

import (
	"fmt"
)

func main() {
	titles := []string{"Poems", "Essays", "Poems", "Plays", "Poems"}
	fmt.Println(titles)
}
Hint 1: the idea

A missing key reads as 0, so counts[title]++ works the first time a title appears. That same rule means counts["Novels"] alone can't tell you whether Novels is in the map. The second result of a lookup can.

Hint 2: a first step

Make the map with counts := map[string]int{}, range over titles, and print counts. You should see map[Essays:1 Plays:1 Poems:3].

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

func main() {
	titles := []string{"Poems", "Essays", "Poems", "Plays", "Poems"}
	counts := map[string]int{}
	for _, title := range titles {
		counts[title]++
	}
	fmt.Println("Poems:", counts["Poems"])
	_, ok := counts["Novels"]
	if !ok {
		fmt.Println("Novels: not logged")
	}
	delete(counts, "Plays")
	fmt.Println("Titles:", len(counts))
}
Text
Poems: 3
Novels: not logged
Titles: 2

_, ok := counts["Novels"] asks only whether the key is there: _ throws away the value, and ok is false for a missing key. len on a map counts its keys, so after the delete only Poems and Essays remain.

Was this article helpful?

Your response is saved on this device.