Pybites Logo Rust Platform

HashMap Entry API

Medium +3 pts

In Python, dictionaries handle missing keys gracefully:

counts = {}
counts['a'] = counts.get('a', 0) + 1  # increment or initialize

# Or with defaultdict
from collections import defaultdict
counts = defaultdict(int)
counts['a'] += 1

Rust's HashMap has an entry API that's even more powerful.

Basic HashMap operations

use std::collections::HashMap;

let mut map: HashMap<String, i32> = HashMap::new();
map.insert("key".to_string(), 42);

let value = map.get("key");         // Option<&i32>
let value = map["key"];             // panics if missing

The Entry API

The entry API lets you inspect and modify an entry in one step:

use std::collections::hash_map::Entry;

// Insert if missing, get mutable reference either way
let count = map.entry("key".to_string()).or_insert(0);
*count += 1;

// Insert with a closure (lazy computation)
map.entry("key".to_string()).or_insert_with(|| expensive_default());

// Modify existing entry
map.entry("key".to_string()).and_modify(|v| *v += 1);

// Combine: modify if exists, insert if missing
map.entry("key".to_string())
    .and_modify(|v| *v += 1)
    .or_insert(1);

Counting pattern

let rolls = [3, 6, 3, 2, 6, 3];
let mut frequencies: HashMap<i32, i32> = HashMap::new();

for roll in rolls {
    *frequencies.entry(roll).or_insert(0) += 1;
}
// {3: 3, 6: 2, 2: 1}

This is Rust's equivalent of Python's Counter or defaultdict(int).


Your Task

  1. word_count(text: &str) -> HashMap<String, i32> — count word frequencies
  2. group_by_length(words: Vec<String>) -> HashMap<usize, Vec<String>> — group words by their …

Login to see the full exercise.