Skip to main content

Maps & Dictionaries

Maps (also known as dictionaries, hash maps, or associative arrays) store key-value pairs. Here's how different languages handle them.

Creating & Accessing Maps​

// Object (string keys only)
const obj = { name: "John", age: 30 };
obj.name; // "John"
obj["age"]; // 30

// Map (any key type)
const map = new Map();
map.set("key", "value");
map.set(42, "number key");
map.set(obj, "object key");

map.get("key"); // "value"
map.has("key"); // true
map.size; // 3
map.delete("key");

// Initialize Map
const map2 = new Map([
["a", 1], ["b", 2], ["c", 3]
]);

// WeakMap (keys are garbage collected)
const weakMap = new WeakMap();
weakMap.set(obj, "data");

Key Takeaways​

  • Built-in syntax support -- JavaScript, Python, Ruby, Go, and Swift have dedicated map/dict literal syntax (e.g., {"name": "John"} in Python, map[string]string{"name": "John"} in Go). C has no built-in hash map and requires libraries like uthash or manual implementation. Literal syntax improves readability and reduces boilerplate. If you work heavily with key-value data (config, caches, JSON), choose a language with first-class map support; for C, plan to integrate a library early.

  • Ordered vs unordered -- Python dicts (3.7+), PHP arrays, and JavaScript Map preserve insertion order. Rust's HashMap is unordered; use BTreeMap for key-ordered iteration. Go maps are unordered; Java's HashMap is unordered (use LinkedHashMap for insertion order). Order matters for reproducible output, LRU caches, or when order encodes meaning. Prefer Python, PHP, or JavaScript Map when order is important; Rust's BTreeMap when you need sorted keys.

  • Safe access patterns -- Go's value, ok := m["key"] returns a boolean for existence; Swift's optional subscript (dict["key"]) returns nil for missing keys; Python's dict.get("key", default) and Ruby's hash.fetch(:key, default) avoid exceptions. Direct indexing in Rust (map["key"]) panics if the key is missing; C++ map["key"] creates an entry with a default value. Use safe access when keys may be absent (e.g., user input, optional config); direct indexing when keys are guaranteed.

  • Key and value types -- JavaScript's plain objects support only string keys; Map allows any type including objects. Python dicts require hashable keys (e.g., strings, numbers, tuples). Go maps require comparable keys. Rust's HashMap needs keys implementing Hash and Eq. Choose Map in JavaScript when you need non-string keys; in Rust, consider BTreeMap for custom key types that don't implement Hash well.

  • Thread safety and concurrency -- Java's ConcurrentHashMap and C#'s ConcurrentDictionary are built for concurrent access. Go maps are not safe for concurrent writes; use sync.Map or mutexes. Rust's ownership model prevents data races without a separate concurrent map type. For shared mutable state across threads, prefer Java or C#; in Go, wrap maps with mutexes or use sync.Map; in Rust, use channels or Arc<Mutex<HashMap>>.