Iterating Over a Hash Map
Part of the Logic & Flow section of Coddy's Rust journey — lesson 31 of 66.
Sometimes you need to examine every key-value pair in your hash map, rather than looking up specific keys. Rust provides a simple way to loop through all the data using a for loop:
for (key, value) in &my_map {
println!("{}: {}", key, value);
}Notice the & before my_map - this creates a reference to the hash map so you can iterate without taking ownership. The loop gives you each key-value pair as a tuple that you can destructure directly in the loop declaration.
Here's a practical example with a price list:
let mut prices = HashMap::new();
prices.insert("apple", 1.20);
prices.insert("banana", 0.80);
for (item, price) in &prices {
println!("{} costs ${:.2}", item, price);
}There's one important detail to remember: hash maps don't guarantee any specific iteration order. The pairs might come out in a different sequence each time you run your program. This is because hash maps prioritize fast lookups over maintaining insertion order, so don't rely on the items appearing in any particular sequence when you iterate.
Challenge
EasyYou will receive an integer n indicating the number of student-score pairs to process. Then you will receive n pairs of inputs: a student name followed by their test score (as an integer). Create a hash map to store the student names as keys and their scores as values. After inserting all pairs, iterate over the hash map and print each student's name and score.
Requirements:
- Import
HashMapfromstd::collections - Create a mutable hash map with types
HashMap<String, i32> - Read the first input and convert it to
i32to get the number of pairs - Use a loop to read
npairs of inputs (student name, then score) - Insert each student name and score into the hash map
- Use a
forloop to iterate over the hash map with&map - Print each student's information in the format:
[name]: [score] - Print the pairs in any order (hash maps don't guarantee order)
Input:
- First line: An integer
n(e.g.,3) - Next
npairs of lines:- Student name (e.g.,
Alice) - Test score as an integer (e.g.,
95)
- Student name (e.g.,
Output:
- One line for each student in the format:
[name]: [score] - The order of output lines may vary between test runs
Cheat sheet
To iterate over all key-value pairs in a hash map, use a for loop with a reference to the map:
for (key, value) in &my_map {
println!("{}: {}", key, value);
}The & before the hash map creates a reference, allowing iteration without taking ownership. The loop destructures each key-value pair as a tuple.
Example with a hash map:
let mut prices = HashMap::new();
prices.insert("apple", 1.20);
prices.insert("banana", 0.80);
for (item, price) in &prices {
println!("{} costs ${:.2}", item, price);
}Important: Hash maps don't guarantee any specific iteration order. The pairs may appear in different sequences each time you run your program, as hash maps prioritize fast lookups over maintaining insertion order.
Try it yourself
use std::collections::HashMap;
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
// Read the number of student-score pairs
let n: i32 = lines.next().unwrap().unwrap().trim().parse().unwrap();
// Create a mutable hash map to store student names and scores
let mut students: HashMap<String, i32> = HashMap::new();
// TODO: Write your code below
// Read n pairs of inputs (student name and score) and insert them into the hash map
// TODO: Iterate over the hash map and print each student's name and score
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together