How do I group items by key using a map?

This example demonstrates how to group items by a specific key using a map in Go. We create a slice of items, then use a map to group those items by a designated key.
Go, grouping, map, example, programming
package main import ( "fmt" ) func main() { items := []struct { Key string Value string }{ {"fruit", "apple"}, {"fruit", "banana"}, {"vegetable", "carrot"}, {"fruit", "date"}, {"vegetable", "eggplant"}, } grouped := make(map[string][]string) for _, item := range items { grouped[item.Key] = append(grouped[item.Key], item.Value) } fmt.Println(grouped) }

Go grouping map example programming