Start learning free

LESSON 231 OF 292 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Two Lists to a Dictionary in Swift: Pairing by Index

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 Dictionary 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 Dictionary. 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

    SWIFT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Two Lists To A Dictionary in Swift, explained

    Problem overview

    The function toDictionary receives an array of strings, names, and an array of integers, scores, of the same length. It returns a dictionary in which each name is a key and the score at the same index is its value. The names are all different, two names may have the same score, and empty arrays give an empty dictionary.

    For names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88], the result pairs Ana with 90, Ben with 75 and Cara with 88.

    Approach: one index reaches both

    A name and its score share a position, so a single loop index i can read names[i] and scores[i] together. For each index, one assignment adds the pair to the dictionary. No lookups or checks are needed, because the names are all different and no key is ever written twice.

    Step by step

    1. Create result as an empty [String: Int] with var.
    2. Loop over the indices with for i in 0..<names.count.
    3. Store the pair: result[names[i]] = scores[i].
    4. Return result after the loop.

    Tracing the example: at i = 0 the dictionary gets "Ana" with 90. At i = 1 it gets "Ben" with 75, and at i = 2 "Cara" with 88. The loop stops because the range ended, and the function returns the three entries.

    This works because the two arrays are parallel: the same position in each describes the same person. The lesson doesn't need to check that the lengths match, since it promises they do. If scores were shorter than names, reading scores[i] past the end would crash.

    The solution in Swift

    class Solution {
        func toDictionary(_ names: [String], _ scores: [Int]) -> [String: Int] {
            var result = [String: Int]()
            for i in 0..<names.count {
                result[names[i]] = scores[i]
            }
            return result
        }
    }
    

    Swift details

    • 0..<names.count is a half-open range: it includes 0 and stops before names.count. For three names it covers 0, 1 and 2, exactly the valid indices. For an empty array the range 0..<0 is empty, so the loop body never runs and the function returns an empty dictionary.
    • Assignment adds or replaces. Assigning to a key through a subscript inserts the entry when the key is new, and replaces the value when the key exists. Here every key is new.
    • Different types on each side. The keys are String and the values Int, matching the function's return type [String: Int].
    • The alternative. Swift has Dictionary(uniqueKeysWithValues: zip(names, scores)), which does the whole job in one expression. The lesson builds the dictionary with a loop to practise the index and the subscript assignment.

    Edge cases and common mistakes

    • Same score twice. ["Zoe", "Adam"] with [60, 60] gives two entries. Equal values are fine; only keys must be unique.
    • Empty input. Two empty arrays give [:], the empty dictionary.
    • A single pair. ["Max"] and [100] give one entry.
    • Using 0...names.count. The closed range includes names.count, one past the last index, and reading names[names.count] crashes the program.
    • Repeated names. If a name appeared twice, the later score would overwrite the earlier one. The lesson guarantees this doesn't happen.

    Testing

    Entries are listed in alphabetical order here for readability.

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