Hash maps: find by key
A hash map (dictionary, associative array) stores key → value pairs and finds a value by its key in O(1) on average. Inside it is an array of buckets. To store a pair, it runs the key through a hash function, which turns the key into a number, and uses that number to pick a bucket. To look the key up later, it computes the same hash and goes straight to the same bucket.
No scanning, no sorting: the key itself says where to look. That's why hash maps are the most used data structure in everyday code.
user id → profile, word → how many times it appears, product code → price. Any time you'd write a loop to 'find the one with this id', a hash map is usually the answer.
In code: Python · Rust
price = {"apple": 0.5, "bread": 1.2}
price["milk"] = 0.9 # insert, O(1) average
price.get("tea", 0) # 0 when missing
counts = {}
for w in "a b a".split():
counts[w] = counts.get(w, 0) + 1 # {'a': 2, 'b': 1}use std::collections::HashMap;
let mut price: HashMap<&str, f64> = HashMap::new();
price.insert("apple", 0.5);
let tea = price.get("tea"); // Option<&f64>: None
let mut counts: HashMap<&str, u32> = HashMap::new();
for w in "a b a".split(' ') {
*counts.entry(w).or_insert(0) += 1;
}- Python: d[key] raises KeyError for a missing key; d.get(key, default) doesn't.
- Rust: get returns an Option, so a missing key is handled explicitly; the entry API inserts or updates in one lookup.