Conceptintro
Map and dictionary
Also called map, dictionary, associative array, hash map, symbol table, key-value store, dict, Map, HashMap, Dictionary<TKey,TValue>, unordered_map, declare -A.
A map, or dictionary, stores pairs of a key and a value, with each key at most once. A program uses the key to find, change or remove its value.
- Applies to
- core-languages
Idea
A map connects keys to values. A phone book is a map: the key is a name and the value is a number. Wikipedia defines it as "an abstract data type that stores a collection of key/value pairs, such that each possible key appears at most once in the collection"1. Other names for the same idea are associative array, dictionary, hash map, symbol table and key-value store. Python calls it a dict, Java and Go call it a map, and C# calls it a Dictionary.
An array finds an item by its position. A map finds a value by its key, and the key can be a string, a number or another value that the map can compare.
# A dict maps each key to one value.
ages = {"ada": 36, "alan": 41}
ages["grace"] = 85 # insert a new key
ages["ada"] = 37 # update: the key "ada" is still there only once
print(ages["alan"], len(ages), "ada" in ages, "bob" in ages)
# A missing key: d[key] raises KeyError, and get gives a default.
print(ages.get("bob"), ages.get("bob", 0))
try:
ages["bob"]
except KeyError as e:
print("KeyError", e)
del ages["alan"]
print(ages)
41 3 True False
None 0
KeyError 'bob'
{'ada': 37, 'grace': 85}
The second write to "ada" does not add a pair. It replaces the value, and the map still has three keys. A read of the key "bob", which is not in the map, is an error with d[key] and gives a default with get.
How it works
The operations. Wikipedia lists the operations of a map1:
- insert or put: "add a new (key,value) pair to the collection, mapping the key to its new value. Any existing mapping is overwritten"1;
- remove or delete: "remove a (key,value) pair from the collection, unmapping a given key from its value"1;
- lookup, find or get: "find the value (if any) that is bound to a given key"1.
Most map types also give the number of pairs, a test for a key, and a loop over the keys, the values or the pairs.
A missing key. The languages do not agree on a read of a key that is not in the map. This is the most important difference between the map types:
- an error. Python
d[key]"Raises a KeyError if key is not in the map"2. In C#, "If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key"3. Rustm[key]panics; - a null value. Java
get"Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key"4. JavaScriptMap.prototype.getgivesundefined; - the zero value. In Go, "If the requested key doesn’t exist, we get the value type’s zero value"5;
- an optional value. Rust
getgivesNonefor a missing key, and Pythongetgives a default: "Return the value for key if key is in the dictionary, else default"2; - an insert. C++
operator[]returns a reference to the value "performing an insertion if such key does not already exist"6.
Rules for keys. A map must be able to tell whether two keys are the same key. A hash map, which is the most common kind, also needs a hash code for each key. Python says "A mapping object maps hashable values to arbitrary objects"2, and "Hashable objects which compare equal must have the same hash value"7. Rust states the same rule as "k1 == k2 -> hash(k1) == hash(k2)"8. Go requires that "The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice"9. So a list is not a key in Python, and a slice is not a key in Go. See hash codes and value equality and identity.
How a map stores its pairs. "The two major solutions to the dictionary problem are hash tables and search trees"1. A hash table uses the hash code of a key to find a bucket, so a lookup takes constant time on average. C++ std::unordered_map is an example: "Search, insertion, and removal of elements have average constant-time complexity. Internally, the elements are not sorted in any particular order, but organized into buckets"10. A search tree keeps the keys sorted and takes logarithmic time. For a few pairs, a list of pairs with a linear search is enough: Wikipedia notes that this "is easy to implement and the constant factors in its running time are small"1.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript uses the JavaScript Map with the type Map<K, V>, and a plain object with the type Record<string, V> or an index signature. The traps of object keys are the same as in JavaScript. No example file exists. |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Standard library | MapOf makes a read-only map and mutableMapOf a mutable one, both from the standard library. m[key] returns null for a missing key, and getValue throws. No example file exists because kotlinc is not installed. |
| SQL | Idiom | A table with a primary key maps each key to one row, and a lookup is a SELECT with WHERE on the key. Some databases also have a map column type, such as hstore and jsonb in PostgreSQL. |
| Bash | Native | Declare -A makes an associative array with string keys. A missing key expands to an empty string, and the test -v tells a missing key from an empty value. No example file exists. |
| PowerShell | Native | The literal @{ a = 1 } makes a hash table with keys that ignore case, and [ordered]@{} keeps the insertion order. The .NET Dictionary class also works. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup. The dl element lists terms and their descriptions, but it is text for a reader, not a map that a program looks up. |
| CSS | Does not apply | CSS has no map values. Custom properties are names with values, but they are style rules, not a data structure. |
| Regular expressions | Does not apply | A regular expression matches text. It has no data structures. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | dict with the literal {k: v}; d[k] raises KeyError, get and setdefault give defaults; insertion order |
| JavaScript | native | Map for any key type, compared with SameValueZero; a plain object with string and symbol keys |
| TypeScript | native | the JavaScript Map<K, V> and the object type Record<K, V> |
| Java | stdlib | the interface Map with HashMap, LinkedHashMap and TreeMap; get returns null for a missing key |
| Kotlin | stdlib | mapOf and mutableMapOf, a LinkedHashMap by default; m[k] gives null for a missing key |
| C# | stdlib | Dictionary<TKey,TValue>; the indexer throws KeyNotFoundException, TryGetValue does not |
| Go | native | map[K]V; a missing key gives the zero value, and v, ok := m[k] tells the cases apart |
| Rust | stdlib | HashMap<K, V> and BTreeMap<K, V>; get returns an Option, the entry API inserts or updates |
| C | idiom | no map type; a hand-written hash table, a library, or POSIX hsearch |
| C++ | stdlib | std::unordered_map (hash) and std::map (tree); operator[] inserts a missing key |
| Bash | native | associative arrays with declare -A, with string keys and string values |
| PowerShell | native | the hash table literal @{} and [ordered]@{} for insertion order |
| SQL | idiom | a table with a primary key; json and hstore values in PostgreSQL |
| Regex | n/a | patterns match text; named groups give a fixed set of names, not a map |
| HTML | n/a | markup; attributes on an element are names and values, but not a data structure |
| CSS | n/a | style rules have no maps; custom properties are names with values in a cascade |
Many scripting languages made the map a built-in type. "Built-in syntactic support for associative arrays was introduced in 1969 by SNOBOL4"1, which called a map a table. AWK arrays are maps: in AWK, "any number or string, not just consecutive integers, may be used as an array index"11. In Bash, "Associative arrays are created using declare -A name"12. C has no map type. POSIX gives hcreate, hsearch and hdestroy, which "shall manage hash search tables"13, but hsearch takes no table argument, so a program can use only one such table at a time.
JavaScript has two kinds of map. "The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value"14. A plain object is also used as a map, but "The keys of an Object must be either a String or a Symbol"14. For property names, "Any other value, including a number, is coerced to a string"15. So obj[1] and obj['1'] are the same entry, and a Map keeps them apart.
The example files show these forms. Python uses get, setdefault and pop, a tuple as a key, a list as a key (a TypeError), the keys 1, 1.0 and True that are one key, and a change during a loop (a RuntimeError). JavaScript compares a Map with an object: number keys, NaN as a key, and an object that has a key from its prototype. Java shows put and its old value, the null problem and Map.of. C# shows the indexer, TryGetValue, Add with a key that is there, and GetValueOrDefault. Go shows the zero value, v, ok, a nil map and a struct key. Rust shows insert, get, remove and entry. C keeps an array of pairs. C++ shows how [] inserts a key and how find, contains and at do not.
# Create a dict with a literal, from pairs, and from keyword arguments.
a = {"x": 1, "y": 2}
b = dict([("x", 1), ("y", 2)])
c = dict(x=1, y=2)
print(a == b == c, len(a))
# Insert, update, read and delete.
a["z"] = 3
a["x"] += 10
print(a["x"], a.get("w"), a.get("w", -1), a.pop("y"), a)
# setdefault inserts only when the key is missing.
print(a.setdefault("x", 0), a.setdefault("w", 0), a)
# Keys must be hashable: a tuple can be a key, a list cannot.
grid = {(0, 0): "start", (2, 3): "end"}
print(grid[(2, 3)])
try:
grid[[0, 0]] = "bad"
except TypeError as e:
print(type(e).__name__)
# Equal keys are the same key: 1, 1.0 and True are equal, so the dict keeps one entry.
d = {1: "int"}
d[1.0] = "float"
d[True] = "bool"
print(d)
# A dict keeps insertion order. Changing a dict during a loop raises RuntimeError.
try:
for k in a:
a[k + "!"] = 0
except RuntimeError:
print("RuntimeError")
True 2
11 None -1 2 {'x': 11, 'z': 3}
11 0 {'x': 11, 'z': 3, 'w': 0}
end
TypeError
{1: 'bool'}
RuntimeError
- Verdict: native. A dict comes from a literal, from pairs or from keyword arguments. d[key] raises KeyError for a missing key, and get and setdefault give a default. A tuple can be a key and a list cannot. 1, 1.0 and True are equal, so they are one key. A change to the keys during a loop raises RuntimeError.
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> m{{"x", 1}, {"y", 2}};
m["z"] = 3;
m["x"] += 10;
std::cout << m["x"] << " " << m.size() << " " << m.contains("y") << "\n";
// operator[] on a missing key inserts the key with a value of 0.
std::cout << m["w"] << " " << m.size() << "\n";
// find and contains do not insert. at throws for a missing key.
std::cout << (m.find("q") == m.end()) << " " << m.contains("q") << " " << m.size() << "\n";
try {
std::cout << m.at("q") << "\n";
} catch (const std::out_of_range &) {
std::cout << "out_of_range\n";
}
// insert does not replace a value; insert_or_assign does.
auto [it, inserted] = m.insert({"x", 99});
std::cout << inserted << " " << it->second << "\n";
m.insert_or_assign("x", 99);
std::cout << m["x"] << "\n";
// erase returns the number of removed items. Copy to a std::map to print sorted.
std::cout << m.erase("y") << " " << m.erase("y") << "\n";
const char *sep = "";
for (const auto &[k, v] : std::map<std::string, int>(m.begin(), m.end())) {
std::cout << sep << k << "=" << v;
sep = " ";
}
std::cout << "\n";
}
11 3 1
0 4
1 0 4
out_of_range
0 11
99
1 0
w=0 x=99 z=3
- Verdict: stdlib. operator[] inserts a missing key with a value of 0, so a read with [] changes the size. find and contains do not insert, and at throws out_of_range. insert does not replace a value, and insert_or_assign does.
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
// A HashMap maps each key to one value. put returns the old value, or null.
Map<String, Integer> m = new HashMap<>();
System.out.println(m.put("x", 1) + " " + m.put("x", 10) + " " + m.put("y", 2));
System.out.println(m.get("x") + " " + m.size() + " " + m.containsKey("y"));
// A missing key gives null, and getOrDefault gives a default.
System.out.println(m.get("w") + " " + m.getOrDefault("w", 0));
// null is ambiguous: a key can also map to null. containsKey tells the two apart.
m.put("n", null);
System.out.println(m.get("n") + " " + m.containsKey("n") + " " + m.containsKey("w"));
m.remove("n");
// A HashMap has no defined order, so copy it to a TreeMap to print it sorted.
System.out.println(new TreeMap<>(m));
// Map.of makes a map that cannot change.
Map<String, Integer> fixed = Map.of("a", 1, "b", 2);
try {
fixed.put("c", 3);
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException");
}
// Unboxing a missing value throws NullPointerException.
try {
int v = m.get("w");
System.out.println(v);
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}
}
}
null 1 null
10 2 true
null 0
null true false
{x=10, y=2}
UnsupportedOperationException
NullPointerException
- Verdict: stdlib. put returns the old value or null, and get returns null for a missing key. A null result is ambiguous, because a key can map to null, so containsKey tells the two cases apart. Map.of makes a map that cannot change, and unboxing a missing Integer throws NullPointerException.
#include <stdio.h>
#include <string.h>
// C has no map type. This map is an array of pairs with a linear search.
struct pair {
const char *key;
int value;
};
struct map {
struct pair items[16];
size_t len;
};
// find returns the index of key, or -1 if the key is not there.
static long find(const struct map *m, const char *key) {
for (size_t i = 0; i < m->len; i++) {
if (strcmp(m->items[i].key, key) == 0) {
return (long)i;
}
}
return -1;
}
// put updates the value of key, or appends a new pair. It returns 0, or -1 if the map is full.
static int put(struct map *m, const char *key, int value) {
long i = find(m, key);
if (i >= 0) {
m->items[i].value = value;
return 0;
}
if (m->len == sizeof m->items / sizeof m->items[0]) {
return -1;
}
m->items[m->len++] = (struct pair){key, value};
return 0;
}
// get writes the value to out and returns 1, or returns 0 if the key is not there.
static int get(const struct map *m, const char *key, int *out) {
long i = find(m, key);
if (i < 0) {
return 0;
}
*out = m->items[i].value;
return 1;
}
// del moves the last pair into the hole, so the order of the pairs changes.
static void del(struct map *m, const char *key) {
long i = find(m, key);
if (i >= 0) {
m->items[i] = m->items[--m->len];
}
}
int main(void) {
struct map m = {.len = 0};
put(&m, "x", 1);
put(&m, "y", 2);
put(&m, "z", 3);
put(&m, "x", 10);
int v = 0;
int found = get(&m, "x", &v);
printf("%d %d %zu\n", found, v, m.len);
found = get(&m, "w", &v);
printf("%d\n", found);
del(&m, "x");
for (size_t i = 0; i < m.len; i++) {
printf("%s=%d\n", m.items[i].key, m.items[i].value);
}
return 0;
}
1 10 3
0
z=3
y=2
- Verdict: idiom. C has no map type. This example keeps an array of key and value pairs with a linear search, so each operation takes linear time. A real program uses a hash table library, or hcreate and hsearch from POSIX, which take no table argument, so a program has one such table at a time.
// A Dictionary maps each key to one value. The indexer inserts or updates.
var d = new Dictionary<string, int> { ["x"] = 1, ["y"] = 2 };
d["x"] = 10;
d["z"] = 3;
Console.WriteLine($"{d["x"]} {d.Count} {d.ContainsKey("y")}");
// Reading a missing key with the indexer throws KeyNotFoundException.
try
{
Console.WriteLine(d["w"]);
}
catch (KeyNotFoundException)
{
Console.WriteLine("KeyNotFoundException");
}
// TryGetValue and GetValueOrDefault do not throw.
Console.WriteLine($"{d.TryGetValue("w", out var w)} {w} {d.GetValueOrDefault("w", -1)}");
// Add throws when the key is already there, and TryAdd returns false.
try
{
d.Add("x", 5);
}
catch (ArgumentException)
{
Console.WriteLine("ArgumentException");
}
Console.WriteLine($"{d.TryAdd("x", 5)} {d["x"]}");
// Remove returns whether a key was removed. Sort the pairs to print them.
Console.WriteLine($"{d.Remove("y")} {d.Remove("y")}");
Console.WriteLine(string.Join(", ", d.OrderBy(p => p.Key).Select(p => $"{p.Key}={p.Value}")));
10 3 True
KeyNotFoundException
False 0 -1
ArgumentException
False 10
True False
x=10, z=3
- Verdict: stdlib. The indexer inserts or updates on a write and throws KeyNotFoundException on a read of a missing key. TryGetValue and GetValueOrDefault do not throw. Add throws for a key that is there, and TryAdd returns false.
// A Map takes keys of any type and keeps insertion order.
const m = new Map([["x", 1], ["y", 2]]);
m.set("z", 3);
m.set("x", 10);
console.log(m.get("x"), m.get("w"), m.has("y"), m.size);
m.delete("y");
console.log([...m]);
// Map keys keep their type: the number 1 and the string "1" are two keys.
const n = new Map();
n.set(1, "number").set("1", "string");
console.log(n.size, n.get(1), n.get("1"));
// Object keys are strings, so 1 and "1" are the same key.
const o = {};
o[1] = "number";
o["1"] = "string";
console.log(Object.keys(o), o[1]);
// A plain object has keys from its prototype, such as toString.
const counts = {};
console.log("toString" in counts, typeof counts.toString);
const safe = Object.create(null);
console.log("toString" in safe);
// Map compares keys with SameValueZero: NaN finds NaN, and an object is found by identity.
const k = { id: 1 };
const byObj = new Map([[NaN, "nan"], [k, "obj"]]);
console.log(byObj.get(NaN), byObj.get(k), byObj.get({ id: 1 }));
10 undefined true 3
[ [ 'x', 10 ], [ 'z', 3 ] ]
2 number string
[ '1' ] string
true function
false
nan obj undefined
- Verdict: native. A Map keeps the type of each key, so 1 and "1" are two keys, and it compares keys with SameValueZero. A plain object turns each key into a string and has keys such as toString from its prototype. Object.create(null) makes an object with no prototype.
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
// A map literal, then insert, update, read and delete.
m := map[string]int{"x": 1, "y": 2}
m["z"] = 3
m["x"] += 10
delete(m, "y")
fmt.Println(m["x"], len(m))
// A missing key gives the zero value. The two-value form tells the cases apart.
v, ok := m["w"]
fmt.Println(m["w"], v, ok)
m["zero"] = 0
v, ok = m["zero"]
fmt.Println(v, ok)
// The order of a range loop over a map is not specified, so sort the keys to print.
fmt.Println(slices.Sorted(maps.Keys(m)))
// A nil map reads like an empty map, but a write panics.
var nilMap map[string]int
fmt.Println(nilMap["a"], len(nilMap))
func() {
defer func() { fmt.Println("panic:", recover()) }()
nilMap["a"] = 1
}()
// A struct of comparable fields can be a key. A slice cannot.
type point struct{ x, y int }
grid := map[point]string{{0, 0}: "start", {2, 3}: "end"}
fmt.Println(grid[point{2, 3}])
}
11 2
0 0 false
0 true
[x z zero]
0 0
panic: assignment to entry in nil map
end
- Verdict: native. A missing key gives the zero value, and the two-value form v, ok tells a missing key from a stored zero. The order of a range loop is not specified, so the example sorts the keys. A nil map reads as empty and panics on a write. A struct of comparable fields can be a key.
use std::collections::{BTreeMap, HashMap};
fn main() {
// insert returns the old value as an Option.
let mut m: HashMap<&str, i32> = HashMap::from([("x", 1), ("y", 2)]);
println!("{:?} {:?}", m.insert("x", 10), m.insert("z", 3));
// get returns an Option, so a missing key is None, not an error.
println!("{:?} {:?} {}", m.get("x"), m.get("w"), m.contains_key("y"));
println!("{}", m.get("w").copied().unwrap_or(0));
// m["w"] would panic, because indexing needs the key to be there.
println!("{}", m["x"]);
// remove returns the value that it took out.
println!("{:?} {:?} {}", m.remove("y"), m.remove("y"), m.len());
// The entry API inserts or updates with one lookup.
*m.entry("x").or_insert(0) += 1;
*m.entry("w").or_insert(0) += 1;
// A HashMap has no order. Collect into a BTreeMap to print the pairs sorted.
let sorted: BTreeMap<_, _> = m.iter().collect();
println!("{sorted:?}");
}
Some(1) None
Some(10) None true
0
10
Some(2) None 2
{"w": 1, "x": 11, "z": 3}
- Verdict: stdlib. insert returns the old value as an Option, get returns an Option, and indexing with a missing key panics. The entry API inserts or updates with one lookup. A HashMap has no order, so the example collects it into a BTreeMap to print it.
Variations and related ideas
- Ordered maps. A tree map, such as Java
TreeMap, RustBTreeMapor C++std::map, keeps its keys sorted. It can find the first key after a given key. See ordered map. - Insertion order. Some maps keep the order in which the keys were added. In Python, "Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end"2. Java
LinkedHashMapand JavaScriptMapdo the same. See insertion-ordered map. - Sets. A set is a map with keys and no values. It answers whether an item is present. See set.
- Multimaps. A multimap can have more than one value for a key. A map of lists does the same job. See multimap.
- Maps with defaults. Python
defaultdict, JavagetOrDefaultand the Rust entry API make the counting and grouping of items short. See count word frequencies and group items by a key. - Immutable maps. Java
Map.ofand Pythontypes.MappingProxyTypegive maps that a program cannot change. See immutability. - Records and JSON objects. A JSON object is a map with string keys. A record or a struct has a fixed set of field names that the compiler knows. A map has keys that the program adds at run time. See JSON.
Pitfalls
- A read that inserts. In C++,
m[k]on a missing key insertskwith a value of 0. A test such asif (m[k] == 0)makes the map larger. Usefind,containsorcountto test for a key. - Null or missing. In Java, "a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null"4. Use
containsKey. A missing value in aMap<String, Integer>also throwsNullPointerExceptionwhen the program unboxes it toint. - A zero that is not there. In Go,
m["w"]gives 0 for a missing key and for a key with the value 0. Use the two-value formv, ok := m["w"]. - Keys that become strings. A JavaScript object turns each key into a string, so the keys
1and'1'collide. An object also has keys from its prototype, such astoString. MDN warns that "An Object has a prototype, so it contains default keys that could collide with your own keys if you're not careful"14. Use aMap. - A key that changes. A hash map stores a key by its hash code. If the key changes after the insert, the map looks in the wrong bucket and does not find it. Java says "The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map"4. C# says that a key "must not change in any way that affects its hash value"16. Use immutable values as keys.
- Equal keys of different types. In Python,
1,1.0andTrueare equal and have the same hash, so they are one key. Afterd = {1: "int"},d[1.0] = "float"andd[True] = "bool", the dict is{1: 'bool'}. The first key stays and the last value wins. - The nil map in Go. "A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic"5. Make the map with
makeor a literal before the first write. - Order. A hash map has no defined order. In Go, "the iteration order is not specified and is not guaranteed to be the same from one iteration to the next"5. Rust
keysvisits "all keys in arbitrary order"8. A test that compares printed maps can fail. Sort the keys before the program prints them. - A change during a loop. In Python, "Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries"2. Java usually throws
ConcurrentModificationException, and C# throwsInvalidOperationExceptionwhen a loop adds a key. Collect the changes in a list and apply them after the loop.
Cost
| Operation | Hash map | Tree map | List of pairs |
|---|---|---|---|
| lookup | constant on average, linear in the worst case | logarithmic | linear |
| insert | constant on average (amortized), linear in the worst case | logarithmic | linear (constant with no test for a duplicate) |
| remove | constant on average, linear in the worst case | logarithmic | linear |
| loop over all pairs | linear, in no defined order | linear, in key order | linear, in list order |
| memory | the pairs and empty buckets | the pairs and two links for each node | the pairs |
The numbers follow the comparison table of Wikipedia1. A hash map is linear in the worst case when many keys have the same hash code. Most languages use a hash map as their default map. .NET says that a lookup is "very fast, close to O(1), because the Dictionary<TKey,TValue> class is implemented as a hash table"16. A hash map also spends time to compute the hash code of each key, so a short list of pairs can be faster for a few keys.
History
SNOBOL4 had tables in 1969, and the scripting languages made maps a part of the language. Wikipedia lists the languages with built-in maps as "Most modern scripting languages, starting with AWK"1, and then Rexx, Perl, PHP, Tcl and JavaScript. Perl calls them hashes, and Python calls them dicts. Compiled languages put maps in the standard library: Java HashMap and C++ std::map, and later C++ std::unordered_map in C++11. Go made map a built-in type.
The order of a map changed over time. Python made insertion order a rule in version 3.7: "Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6"2. Go went the other way. The order of a loop over a map is not specified, and it can change from one loop to the next5. Rust uses a hash function with a random seed: "The algorithm is randomly seeded"8.
References
- Associative array, Wikipedia, Introduction; Operations; Implementation; Ordered dictionary; Language support
- Built-in Types, The Python Standard Library, Mapping Types, dict
- Dictionary<TKey,TValue>.Item[TKey] property, .NET API reference, Remarks
- Interface Map, Java SE 25 API, Description; get
- Andrew Gerrand, Go maps in action, The Go Blog, 2013, Declaration and initialization; Working with maps; Iteration order
- std::unordered_map::operator[], cppreference.com, Description
- Glossary, Python documentation, hashable
- Struct HashMap, The Rust Standard Library, Description; insert; keys
- The Go Programming Language Specification, Map types
- std::unordered_map, cppreference.com, Description
- Introduction to Arrays, The GNU Awk User's Guide, Full text
- Bash Reference Manual, Arrays
- hcreate, hdestroy, hsearch, The Open Group Base Specifications Issue 8, Description
- Map, MDN Web Docs, Description; Key equality; Objects vs. Maps
- Property accessors, MDN Web Docs, Property names
- Dictionary<TKey,TValue> class, .NET API reference, Definition; Remarks
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag S42X6B Edit this page History Report an error Markdown