1

I would like to take an alphanumeric string, iterate character by character, and lookup each character in a HashMap.

Here is how I would do it in Python:

lookup: dict = {
    'J': 5,
    'H': 17,
    '4': 12
}

s: str = 'JH4'

looked_up: list[str] = [lookup[c] for c in s]
print(looked_up)
[5, 17, 12]

My attempt in Rust

use std::collections::HashMap;

fn main()
{

    let lookup: Hashmap<char, u32> = HashMap::from([
        ('J', 5),
        ('H', 17),
        ('4', 12)
    ]);

    let s = String::from("JH4");
    for c in s.chars()
    {
        // Stuck here
        // I would like to look up each character from s via the lookup key and return an array of
        // the values returned.
    }

}

1 Answer 1

2

chars() returns an iterator, so you can just map over each element, indexing the map:

use std::collections::HashMap;

fn main() {
    let lookup: HashMap<char, u32> = HashMap::from([
        ('J', 5),
        ('H', 17),
        ('4', 12)
    ]);

    let s = String::from("JH4");

    let looked_up: Vec<_> = s.chars().map(|c| lookup[&c]).collect();
    dbg!(looked_up);
}

This will panic if c is not a key of the map, so you may want to explicitly handle that case instead:

let looked_up: Vec<_> = s.chars().map(
    // return the value from the map, or if none exists,
    // return 0 by default
    |c| lookup.get(&c).unwrap_or(0)
).collect();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Just started playing around in Rust today. When typing Vec<_> is there a reason for the _ or should I type it to the values of my lookup, e.g. u32?
Vec<_> essentially tells the compiler "you already know what the inner type should be (because it's defined by the hashmap), so fill it in for me". You can, of course, just put Vec<u32> instead to be more explicit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.