Start learning free

LESSON 230 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Two Lists to a Dictionary in Go: Building a Map

Practice Read the full explanation

Given an array of strings names and an array of integers scores of the same length, pair each name with the score at the same index. Return a map where names[i] is a key and scores[i] is its value.

The names are all different, while two names can have the same score. If names and scores are empty, return an empty map. The order of the entries doesn't matter.

Example 1:

Input: names = ["Ana", "Ben", "Cara"], scores = [90, 75, 88]
Output: {"Ana": 90, "Ben": 75, "Cara": 88}
Explanation: "Ana" is at index 0 in names, and the score at index 0 is 90. The same goes for "Ben" with 75 and "Cara" with 88.

Example 2:

Input: names = ["Zoe", "Adam"], scores = [60, 60]
Output: {"Zoe": 60, "Adam": 60}
Explanation: Two names with the same score are two different entries.

Example 3:

Input: names = ["Max"], scores = [100]
Output: {"Max": 100}
Explanation: One name gives a single entry.
STEP 1 OF 4
    Ctrl + Enter to check

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Two Lists To A Dictionary in Go, explained

    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

    1. Create an empty map. result := map[string]int{} has string keys and integer values.
    2. Loop over the indices. for i := 0; i < len(names); i++ is Go's counting loop: start at 0, continue while i is 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 use range over values.
    3. Store the pair. result[names[i]] = scores[i] uses the name as the key and the score as the value.
    4. Return result after the loop.

    Tracing the example

    With ["Ana", "Ben", "Cara"] and [90, 75, 88], the map after each pass of the loop is:

    iresult after the assignment
    0map[Ana:90]
    1map[Ana:90 Ben:75]
    2map[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). If scores were 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 names gives 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 is map[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.Println shows a map sorted by key; the map itself has no order, and a range over it visits entries in random order.

    Edge cases and common mistakes

    • Same score, different names. ["Zoe", "Adam"] with [60, 60] gives map[Adam:60 Zoe:60]: values may repeat, only keys must be unique.
    • One pair. ["Max"] and [100] give map[Max:100].
    • Swapping key and value. result[scores[i]] = names[i] doesn't compile, because the map's key type is string. Keys come from names.
    • Using <= in the loop condition runs one step too far and panics on names[len(names)].
    • Writing into a nil map. Declaring var result map[string]int without creating it makes the first assignment panic.

    Testing

    • ["Ana", "Ben", "Cara"] with [90, 75, 88] gives map[Ana:90 Ben:75 Cara:88].
    • ["Zoe", "Adam"] with [60, 60] gives map[Adam:60 Zoe:60].
    • ["Max"] with [100] gives map[Max:100].
    • Two empty slices give map[].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free