Nested Maps Group Counts By Two Keys

Aggregate tickets into map[string]map[string]int keyed by region then status, sorting outer keys because map range order is randomized.

GoData Integrity

Code

gosnippet
47 lines
package main

import (
	"fmt"
	"sort"
)

type Ticket struct {
	Region string
	Status string // "open" or "closed"
	Count  int
}

func main() {
	tickets := []Ticket{
		{"eu", "open", 3},
		{"us", "closed", 5},
		{"eu", "closed", 2},
		{"us", "open", 1},
		{"eu", "open", 4},
	}

	// nested map: region -> status -> summed count
	byRegion := map[string]map[string]int{}
	for _, t := range tickets {
		if byRegion[t.Region] == nil {
			byRegion[t.Region] = map[string]int{}
		}
		byRegion[t.Region][t.Status] += t.Count
	}

	regions := make([]string, 0, len(byRegion))
	for region := range byRegion {
		regions = append(regions, region)
	}
	sort.Strings(regions) // map range order is random; sort for stable output

	// inner keys walk a fixed list so prints never depend on map order
	statuses := []string{"open", "closed"}
	for _, region := range regions {
		for _, status := range statuses {
			if total, ok := byRegion[region][status]; ok {
				fmt.Printf("%s/%s: %d\n", region, status, total)
			}
		}
	}
}

Walking through the code — Nested Maps Group Counts By Two Keys

The part that does the work is the function main — everything else is wiring.

Repetition is confined to for _, t := range tickets — the rest of the file is straight-line.

Watch out for

  • Nothing to pull in: the runtime itself supplies everything this file needs.

Applying it

The one declaration that anchors the file: func main()

Statements that matter

sort.Strings(regions) // map range order is random; sort for stable output
for _, status := range statuses {
	if total, ok := byRegion[region][status]; ok {
		fmt.Printf("%s/%s: %d\n", region, status, total)
	}
}
for region := range byRegion {
	regions = append(regions, region)
}

Interactive Tools for This Topic

FAQ

How do you run Nested Maps Group Counts By Two Keys?
It runs as-is — treat the file as the whole program and execute it.