Problem overview
The function toDictionary receives a slice of strings, names, and a slice of integers, scores, of the same length. It returns a map[string]int in which each names[i] is a key and scores[i] is its value. Names are all different, two names may share a score, and empty slices give an empty map.
For ["Ana", "Ben", "Cara"] and [90, 75, 88], the result is map[Ana:90 Ben:75 Cara:88]. The name at index 0 pairs with the score at index 0, and so on.
Approach: one index reaches both slices
Because a name and its score sit at the same position, a single loop counter i is enough. At each position, read the name from one slice and the score from the other, and store the pair in the map. Assigning to a key that isn't in the map yet adds it, so the map grows as the loop runs.
Step by step
- Create an empty map.
result := map[string]int{}has string keys and integer values. - Loop over the indices.
for i := 0; i < len(names); i++is Go's counting loop: start at 0, continue whileiis less than the number of names, add 1 each time. This version needs the index itself, because the same position is used in two slices, so it doesn't userangeover values. - Store the pair.
result[names[i]] = scores[i]uses the name as the key and the score as the value. - Return
resultafter the loop.
Tracing the example
With ["Ana", "Ben", "Cara"] and [90, 75, 88], the map after each pass of the loop is:
| i | result after the assignment |
|---|---|
| 0 | map[Ana:90] |
| 1 | map[Ana:90 Ben:75] |
| 2 | map[Ana:90 Ben:75 Cara:88] |
When i reaches 3, the condition i < len(names) is false and the loop ends.
The solution in Go
func toDictionary(names []string, scores []int) map[string]int {
result := map[string]int{}
for i := 0; i < len(names); i++ {
result[names[i]] = scores[i]
}
return result
}
Go details worth knowing
- Empty input. With two empty slices the loop body never runs, and the function returns the empty map, which prints as
map[]. - Different lengths. The loop uses
len(names). Ifscoreswere shorter,scores[i]would panic with an index-out-of-range error. The lesson guarantees equal lengths. - Another way to write the loop.
for i := range namesgives the same indices with less to type. Both are idiomatic. - Duplicate names. Assigning to an existing key replaces its value. For
["a", "b", "a"]and[1, 2, 3]the result ismap[a:3 b:2]: the later score overwrites the earlier one. The lesson promises distinct names, so this doesn't come up, but it explains why keys must be unique for no data to be lost. - Printing.
fmt.Printlnshows a map sorted by key; the map itself has no order, and arangeover it visits entries in random order.
Edge cases and common mistakes
- Same score, different names.
["Zoe", "Adam"]with[60, 60]givesmap[Adam:60 Zoe:60]: values may repeat, only keys must be unique. - One pair.
["Max"]and[100]givemap[Max:100]. - Swapping key and value.
result[scores[i]] = names[i]doesn't compile, because the map's key type isstring. Keys come fromnames. - Using
<=in the loop condition runs one step too far and panics onnames[len(names)]. - Writing into a nil map. Declaring
var result map[string]intwithout creating it makes the first assignment panic.
Testing
["Ana", "Ben", "Cara"]with[90, 75, 88]givesmap[Ana:90 Ben:75 Cara:88].["Zoe", "Adam"]with[60, 60]givesmap[Adam:60 Zoe:60].["Max"]with[100]givesmap[Max:100].- Two empty slices give
map[].
