Start learning free

LESSON 233 OF 293 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Two Lists to a HashMap in Rust: Pairing Names with Scores

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

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Two Lists To A Dictionary in Rust, explained

    Problem overview

    The function to_dictionary receives a vector of strings, names, and a vector of integers, scores, of the same length. It returns a HashMap<String, i32> in which names[i] is a key and scores[i] is its value. The names are all different, two names may share a score, and two empty vectors give an empty map. The order of the entries doesn't matter.

    For ["Ana", "Ben", "Cara"] and [90, 75, 88], the map holds Ana: 90, Ben: 75 and Cara: 88.

    Approach: one index, two vectors

    A name and its score sit at the same position in their vectors. So one loop over the positions reaches both of them: at each index i, insert the pair (names[i], scores[i]) into the map. The map ends up with one entry per name.

    Step by step

    1. Create the empty map result, a mutable HashMap<String, i32>.
    2. Loop over the indices with for i in 0..names.len(). The range 0..names.len() covers 0 up to, but not including, the length.
    3. Insert the pair. The key is names[i].clone() and the value is scores[i].
    4. Return result after the loop.

    The solution in Rust

    impl Solution {
        fn to_dictionary(names: Vec<String>, scores: Vec<i32>) -> HashMap<String, i32> {
            let mut result: HashMap<String, i32> = HashMap::new();
            for i in 0..names.len() {
                result.insert(names[i].clone(), scores[i]);
            }
            return result;
        }
    }
    

    The Rust details worth a closer look:

    • Why clone(). The map's keys must own their strings. Indexing names[i] can't move a String out of the vector, so clone() makes a copy for the map to keep. The scores are i32 values, which are copied automatically.
    • Ranges are half-open. 0..names.len() excludes the end, so the last index used is names.len() - 1. For an empty vector the range is empty, the loop doesn't run, and the result is an empty map.
    • Indexing is bounds-checked. If scores were shorter than names, scores[i] would panic. The lesson guarantees equal lengths.
    • Another way. names.into_iter().zip(scores).collect() builds the same map without indices. The lesson's loop makes each step visible.

    Tracing the example

    With names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88], the loop runs for i equal to 0, 1 and 2. At 0 it inserts "Ana" with 90, at 1 "Ben" with 75, and at 2 "Cara" with 88. The map then has three entries. The loop does one insertion per name, so the time grows in proportion to the number of names.

    The map doesn't remember the order of insertion. Printing it may list the entries in any order, and that order can differ from one run to the next.

    Looking a score up afterwards is just as direct: result["Ben"] gives 75, and result.get("Zed") returns None for a name that isn't there, where indexing with a missing key would panic.

    Edge cases and common mistakes

    • Same score, different names. ["Zoe", "Adam"] with [60, 60] gives two entries. Only keys must be unique; values can repeat.
    • Empty input. Two empty vectors return an empty map.
    • Repeated names. The lesson rules them out, but with a repeated name, insert would replace the earlier score: ["Ana", "Ana"] with [1, 2] gives Ana: 2.
    • Using 0..=names.len(). The inclusive range would go one index too far, and indexing it would panic.

    Testing

    Sorted by name, the entries are:

    • ["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.
    • Two empty vectors give an empty map.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free