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.
}
}
CodePudding user response:
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();