Conceptcore
Insertion-ordered map
Also called ordered dictionary, linked hash map, LinkedHashMap, OrderedDict, OrderedDictionary, index map, IndexMap.
An insertion-ordered map gives its keys back in the order in which they were added. Python dict, JavaScript Map and Java LinkedHashMap work this way, and Go and C++ maps do not.
- Applies to
- core-languages
Idea
A hash table puts each key in a bucket chosen by its hash code, so a loop over the table visits the keys in an order that looks random. An insertion-ordered map remembers a second thing: the order in which the keys were added. A loop gives the oldest key first and the newest key last. This makes the output of a program stable and easy to read, and it keeps the order of fields when a program reads and writes JSON or a configuration file.
Wikipedia names two kinds of ordered dictionary. In one, the keys are sorted, which is an ordered map. In the other, "The order of enumeration is key-independent and is instead based on the order of insertion"1. Wikipedia gives the .NET Framework ordered dictionary, the Java LinkedHashMap and Python as examples. In Python every dict works this way: "Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end."2
# A Python dict remembers the order in which its keys were added.
stock = {}
stock["pear"] = 4
stock["apple"] = 7
stock["fig"] = 2
print(list(stock))
# Changing the value of a key does not move the key.
stock["pear"] = 9
print(list(stock.items()))
# A key that is removed and added again goes to the end.
del stock["pear"]
stock["pear"] = 1
print(list(stock))
# The first and the last key, and the keys in reverse order.
print(next(iter(stock)), next(reversed(stock)), list(reversed(stock)))
['pear', 'apple', 'fig']
[('pear', 9), ('apple', 7), ('fig', 2)]
['apple', 'fig', 'pear']
apple pear ['pear', 'fig', 'apple']
The keys come back as pear, apple, fig, which is the order of the code, not the order of the alphabet. The update of pear keeps its place. The delete and the new insert move it to the end.
How it works
A hash table and a linked list. Java LinkedHashMap is a "Hash table and linked list implementation of the Map interface, with well-defined encounter order"3. Each entry is in a bucket for fast lookup, and each entry is also on a doubly linked list: "This linked list defines the encounter order (the order of iteration), which is normally the order in which keys were inserted into the map"3. An insert appends the entry to the end of the list. A delete unlinks it from the list in constant time, because the entry knows its neighbors.
An array of entries and a table of indexes. CPython and the Rust crate indexmap keep the entries in an array in insertion order. A separate hash table maps each key to its position in the array. A loop reads the array from start to end. A delete must leave a hole in the array, or move the later entries down, or move the last entry into the hole. The last choice is fast but changes the order. The example files show this.
Rules for updates and deletes. The languages agree on two rules. First, a new value for a key that is already in the map does not move the key. Java says that the "encounter order is not affected if a key is re-inserted into the map with the put method"3. Second, a key that is removed and then added again is a new key, so it goes to the end. To move a key to the end on purpose, remove it and add it again, or use a method such as Python OrderedDict.move_to_end.
Access order. A variant moves a key to the end each time a program reads it. Then the first key is the one that was not used for the longest time. Java LinkedHashMap has a constructor for this, and "This kind of map is well-suited to building LRU caches"3. The method removeEldestEntry can remove the oldest entry after each insert, which keeps the cache at a fixed size.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Idiom | |
| Java | Standard library | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript uses the JavaScript Map, which iterates its keys in insertion order. Map<K, V> types the keys and the values. No example file exists. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Standard library | MutableMapOf, mapOf and linkedMapOf return maps that keep the entry iteration order. On the JVM they are a java.util.LinkedHashMap. No example file exists because kotlinc is not installed. |
| SQL | Idiom | A table has no row order without ORDER BY. A table keeps insertion order with an identity or sequence column, and a query sorts by that column. |
| Bash | Idiom | Bash associative arrays give their keys in no defined order. A script keeps an indexed array of keys in insertion order next to the associative array. No example file exists. |
| PowerShell | Standard library | The [ordered] type accelerator, added in PowerShell 3.0, makes an OrderedDictionary whose keys keep the order in which they are listed. A plain @{} hashtable has no fixed order. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup and has no data structures. |
| CSS | Does not apply | CSS has no data structures. |
| Regular expressions | Does not apply | A regular expression matches text. It has no maps. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | every dict; collections.OrderedDict adds move_to_end and order-aware equality |
| JavaScript | native | Map iterates in insertion order; a plain object puts index-like keys first |
| TypeScript | native | the JavaScript Map, typed as Map<K, V> |
| Java | stdlib | LinkedHashMap, a SequencedMap since Java 21; HashMap has no order |
| Kotlin | stdlib | mutableMapOf and mapOf keep the order; on the JVM they are a LinkedHashMap |
| C# | stdlib | OrderedDictionary<TKey,TValue> since .NET 9; Dictionary has no defined order |
| Go | idiom | a map has no order; keep a slice of keys next to the map |
| Rust | idiom | HashMap has no order; a Vec of entries with an index, or the indexmap crate |
| C | idiom | a hash table whose entries are also on a linked list |
| C++ | idiom | std::unordered_map has no order; a std::list with a map of iterators into it |
| Bash | idiom | an indexed array of keys next to an associative array |
| PowerShell | stdlib | [ordered]@{...} makes an OrderedDictionary; @{...} has no fixed order |
| SQL | idiom | rows have no order without ORDER BY; an identity column records the insert order |
| Regex | n/a | patterns match text and have no maps |
| HTML | n/a | markup with no data structures |
| CSS | n/a | style rules with no data structures |
Python made the order a rule of the language in 3.7: "Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6."2 The release notes say that "the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec"4. OrderedDict is still in the standard library. Its documentation says "The regular dict was designed to be very good at mapping operations. Tracking insertion order was secondary."5 and "The OrderedDict was designed to be good at reordering operations."5
JavaScript has two kinds of map with different rules. MDN says that "The Map object holds key-value pairs and remembers the original insertion order of the keys"6, and that "A Map object iterates entries, keys, and values in the order of entry insertion"6. A plain object also has an order, but MDN warns: "Although the keys of an ordinary Object are ordered now, this was not always the case, and the order is complex. As a result, it's best not to rely on property order."6
Go, C# and Rust make no promise for their main map type. The Go blog says that with a range loop "the iteration order is not specified and is not guaranteed to be the same from one iteration to the next"7, and that a program that needs a stable order "must maintain a separate data structure that specifies that order"7. For the C# Dictionary, "The order in which the items are returned is undefined"8. Rust HashMap gives "An iterator visiting all keys in arbitrary order"9. C# added OrderedDictionary<TKey,TValue> in .NET 9. It "Represents a collection of key/value pairs that are accessible by the key or index"10.
PowerShell has a short form for the ordered type. "Beginning in PowerShell 3.0, you can use the [ordered] type accelerator to create an [System.Collections.Specialized.OrderedDictionary] object in PowerShell. Ordered dictionaries differ from hashtables in that the keys always appear in the order in which you list them. The order of keys in a hashtable isn't deterministic."11 Kotlin mutableMapOf "Returns an empty new MutableMap. The returned map preserves the entry iteration order."12 In PHP, every array keeps insertion order: "An array in PHP is actually an ordered map."13
The example files show these forms. Python compares dict and OrderedDict equality and builds a small LRU cache with move_to_end. JavaScript shows the order of a Map, an LRU cache with delete and set, and the different key order of a plain object. Java uses LinkedHashMap, the Java 21 SequencedMap methods and an access-order LRU cache. C# uses the index methods of OrderedDictionary<TKey,TValue>. Go keeps a slice of keys. Rust builds a small index map and compares swap_remove with shift_remove. C links the entries of a hash table on a list. C++ builds an LRU cache from std::list and std::unordered_map.
from collections import OrderedDict
# dict keeps insertion order. Two dicts with the same pairs are equal in any order.
a = {"x": 1, "y": 2}
b = {"y": 2, "x": 1}
print(list(a), list(b), a == b)
# OrderedDict compares the order too.
oa, ob = OrderedDict(a), OrderedDict(b)
print(oa == ob, oa == b)
# move_to_end and popitem(last=False) reorder the keys in constant time.
od = OrderedDict.fromkeys("abcde")
od.move_to_end("b")
od.move_to_end("e", last=False)
print("".join(od))
print(od.popitem(last=False)[0], od.popitem()[0], "".join(od))
# A small least-recently-used cache: a hit moves the key to the end,
# and a full cache drops the first key.
class LRU:
def __init__(self, size):
self.size, self.data = size, OrderedDict()
def get(self, k):
if k not in self.data:
return None
self.data.move_to_end(k)
return self.data[k]
def put(self, k, v):
self.data[k] = v
self.data.move_to_end(k)
if len(self.data) > self.size:
self.data.popitem(last=False)
c = LRU(2)
c.put("a", 1)
c.put("b", 2)
c.get("a")
c.put("c", 3)
print(list(c.data), c.get("b"))
# Changing a dict while a loop reads it is an error.
d = {"a": 1}
try:
for k in d:
d["b"] = 2
except RuntimeError as e:
print(type(e).__name__)
['x', 'y'] ['y', 'x'] True
False True
eacdb
e b acd
['a', 'c'] None
RuntimeError
- Verdict: native. Since Python 3.7 a dict keeps insertion order. An update keeps the place of a key, and a key that is removed and added again goes to the end. collections.OrderedDict adds move_to_end and popitem(last=False), and its equality test compares the order. The example builds a small LRU cache with it.
#include <iostream>
#include <list>
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
// std::unordered_map has no order. A std::list holds the order and the map points
// into the list. This is the usual LRU cache: a hit splices the entry to the back.
class Lru {
std::size_t cap;
std::list<std::pair<std::string, int>> order;
std::unordered_map<std::string, std::list<std::pair<std::string, int>>::iterator> pos;
public:
explicit Lru(std::size_t c) : cap(c) {}
std::optional<int> get(const std::string& k) {
auto it = pos.find(k);
if (it == pos.end()) return std::nullopt;
order.splice(order.end(), order, it->second); // constant time, no copy
return it->second->second;
}
void put(const std::string& k, int v) {
if (auto it = pos.find(k); it != pos.end()) {
it->second->second = v;
order.splice(order.end(), order, it->second);
return;
}
order.emplace_back(k, v);
pos[k] = std::prev(order.end());
if (order.size() > cap) {
pos.erase(order.front().first);
order.pop_front();
}
}
void show() const {
for (const auto& [k, v] : order) std::cout << k << "=" << v << " ";
std::cout << "end\n";
}
};
int main() {
Lru c(3);
c.put("a", 1);
c.put("b", 2);
c.put("c", 3);
c.show();
c.get("a");
c.show();
c.put("d", 4);
c.show();
std::cout << c.get("b").has_value() << " " << c.get("c").value() << "\n";
c.show();
}
a=1 b=2 c=3 end
b=2 c=3 a=1 end
c=3 a=1 d=4 end
0 3
a=1 d=4 c=3 end
- Verdict: idiom. std::unordered_map has no order, and the standard library has no insertion-ordered map. A std::list holds the order and the map holds iterators into the list. splice moves an entry to the back in constant time, which gives an LRU cache.
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
// An access-order LinkedHashMap with removeEldestEntry is a small LRU cache.
static class Lru<K, V> extends LinkedHashMap<K, V> {
private final int size;
Lru(int size) {
super(16, 0.75f, true);
this.size = size;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > size;
}
}
public static void main(String[] args) {
// LinkedHashMap keeps insertion order. HashMap does not promise any order.
Map<String, Integer> m = new LinkedHashMap<>();
m.put("pear", 4);
m.put("apple", 7);
m.put("fig", 2);
System.out.println(m);
// Putting a key again does not move it. Remove and put moves it to the end.
m.put("pear", 9);
System.out.println(m);
m.remove("pear");
m.put("pear", 1);
System.out.println(m.keySet());
// Java 21 added SequencedMap: first and last entries, putFirst, reversed.
LinkedHashMap<String, Integer> s = new LinkedHashMap<>(m);
s.putFirst("kiwi", 5);
System.out.println(s.firstEntry() + " " + s.lastEntry() + " " + s.reversed().keySet());
// A copy into a LinkedHashMap keeps the order of the source.
Map<String, Integer> copy = new LinkedHashMap<>(s);
System.out.println(copy.keySet().equals(s.keySet()) + " " + copy.equals(new HashMap<>(s)));
Lru<String, Integer> lru = new Lru<>(2);
lru.put("a", 1);
lru.put("b", 2);
lru.get("a");
lru.put("c", 3);
System.out.println(lru.keySet());
}
}
{pear=4, apple=7, fig=2}
{pear=9, apple=7, fig=2}
[apple, fig, pear]
kiwi=5 pear=1 [pear, fig, apple, kiwi]
true true
[a, c]
- Verdict: stdlib. LinkedHashMap keeps a doubly linked list through its entries. Java 21 added SequencedMap with firstEntry, lastEntry, putFirst and reversed. An access-order LinkedHashMap with removeEldestEntry is an LRU cache. HashMap promises no order.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A hash table whose entries are also on a doubly linked list in insertion
order. This is the design of Java's LinkedHashMap. */
#define NB 8
struct entry {
char key[16];
int val;
struct entry *bnext; /* next entry in the same bucket */
struct entry *prev, *next; /* insertion-order list */
};
static struct entry *buckets[NB];
static struct entry *head, *tail;
static unsigned hash(const char *s) {
unsigned h = 2166136261u;
for (; *s; s++) h = (h ^ (unsigned char)*s) * 16777619u;
return h % NB;
}
static struct entry *find(const char *k) {
for (struct entry *e = buckets[hash(k)]; e; e = e->bnext)
if (strcmp(e->key, k) == 0) return e;
return NULL;
}
static void put(const char *k, int v) {
struct entry *e = find(k);
if (e) { e->val = v; return; } /* an update keeps its place */
e = calloc(1, sizeof *e);
snprintf(e->key, sizeof e->key, "%s", k);
e->val = v;
unsigned b = hash(k);
e->bnext = buckets[b];
buckets[b] = e;
e->prev = tail; /* append to the order list */
if (tail) tail->next = e; else head = e;
tail = e;
}
static void del(const char *k) {
unsigned b = hash(k);
for (struct entry **p = &buckets[b]; *p; p = &(*p)->bnext) {
struct entry *e = *p;
if (strcmp(e->key, k) != 0) continue;
*p = e->bnext;
/* unlink from the order list in constant time */
if (e->prev) e->prev->next = e->next; else head = e->next;
if (e->next) e->next->prev = e->prev; else tail = e->prev;
free(e);
return;
}
}
static void show(void) {
for (struct entry *e = head; e; e = e->next)
printf("%s=%d%s", e->key, e->val, e->next ? " " : "\n");
}
int main(void) {
put("pear", 4);
put("apple", 7);
put("fig", 2);
show();
put("pear", 9);
show();
del("pear");
put("pear", 1);
show();
printf("first %s, last %s\n", head->key, tail->key);
while (head) del(head->key);
printf("empty %d\n", head == NULL && tail == NULL);
return 0;
}
pear=4 apple=7 fig=2
pear=9 apple=7 fig=2
apple=7 fig=2 pear=1
first apple, last pear
empty 1
- Verdict: idiom. C has no maps. The example is a chained hash table whose entries are also on a doubly linked list in insertion order, which is the design of Java LinkedHashMap. An update keeps the place, and a delete unlinks the entry in constant time.
using System.Collections.Specialized;
// OrderedDictionary<TKey,TValue> (.NET 9) keeps insertion order and has an index.
var m = new OrderedDictionary<string, int>();
m.Add("pear", 4);
m.Add("apple", 7);
m["fig"] = 2;
Console.WriteLine(string.Join(" ", m.Keys));
// Setting an existing key keeps its place. Remove and add moves it to the end.
m["pear"] = 9;
Console.WriteLine(string.Join(" ", m));
m.Remove("pear");
m.Add("pear", 1);
Console.WriteLine(string.Join(" ", m.Keys));
// Index operations: the entry at a position, the position of a key, insert at a position.
Console.WriteLine($"{m.GetAt(0).Key} {m.IndexOf("fig")} {m.IndexOf("kiwi")}");
m.Insert(0, "kiwi", 5);
Console.WriteLine(string.Join(" ", m.Keys));
// Dictionary<TKey,TValue> does not promise an order. Two dictionaries with the
// same pairs in a different order are equal as sets of pairs.
var d1 = new Dictionary<string, int> { ["x"] = 1, ["y"] = 2 };
var d2 = new Dictionary<string, int> { ["y"] = 2, ["x"] = 1 };
Console.WriteLine(d1.Count == d2.Count && !d1.Except(d2).Any());
// The older non-generic OrderedDictionary stores object keys and values.
var old = new OrderedDictionary { { "b", 1 }, { "a", 2 } };
Console.WriteLine(string.Join(" ", old.Keys.Cast<string>()));
pear apple fig
[pear, 9] [apple, 7] [fig, 2]
apple fig pear
apple 1 -1
kiwi apple fig pear
True
b a
- Verdict: stdlib. OrderedDictionary<TKey,TValue> from .NET 9 keeps insertion order and adds GetAt, IndexOf and Insert by position. Dictionary<TKey,TValue> does not promise an order. The older non-generic OrderedDictionary holds object keys and values.
// A Map iterates its keys in insertion order.
const m = new Map();
m.set("pear", 4).set("apple", 7).set("fig", 2);
console.log([...m.keys()].join(" "));
// Setting a key that exists keeps its place. Delete and set moves it to the end.
m.set("pear", 9);
console.log([...m].join(" "));
m.delete("pear");
m.set("pear", 1);
console.log([...m.keys()].join(" "));
// The first key is the oldest. This makes a small LRU cache.
function touch(cache, k, v, size) {
cache.delete(k);
cache.set(k, v);
if (cache.size > size) cache.delete(cache.keys().next().value);
}
const lru = new Map();
touch(lru, "a", 1, 2);
touch(lru, "b", 2, 2);
touch(lru, "a", 1, 2);
touch(lru, "c", 3, 2);
console.log([...lru.keys()].join(" "));
// A plain object is different: keys that look like array indexes come first,
// in number order, and then the other strings in insertion order.
const o = { b: 1, 10: 2, a: 3, 2: 4 };
console.log(Object.keys(o).join(" "));
// JSON.stringify writes the keys of an object in the same order.
console.log(JSON.stringify(Object.fromEntries(m)));
pear apple fig
pear,9 apple,7 fig,2
apple fig pear
a c
2 10 b a
{"apple":7,"fig":2,"pear":1}
- Verdict: native. A Map iterates in insertion order. Setting an existing key keeps its place, and delete then set moves it to the end, which makes a small LRU cache. A plain object puts keys that look like array indexes first, in number order.
package main
import (
"fmt"
"slices"
"strings"
)
// Go maps do not keep any order, so this type keeps a slice of keys next to the map.
type Ordered struct {
keys []string
vals map[string]int
}
func NewOrdered() *Ordered { return &Ordered{vals: map[string]int{}} }
func (o *Ordered) Set(k string, v int) {
if _, ok := o.vals[k]; !ok {
o.keys = append(o.keys, k)
}
o.vals[k] = v
}
// Delete must also remove the key from the slice. This is linear.
func (o *Ordered) Delete(k string) {
if _, ok := o.vals[k]; !ok {
return
}
delete(o.vals, k)
o.keys = slices.DeleteFunc(o.keys, func(s string) bool { return s == k })
}
func (o *Ordered) String() string {
parts := make([]string, 0, len(o.keys))
for _, k := range o.keys {
parts = append(parts, fmt.Sprintf("%s=%d", k, o.vals[k]))
}
return strings.Join(parts, " ")
}
func main() {
o := NewOrdered()
o.Set("pear", 4)
o.Set("apple", 7)
o.Set("fig", 2)
fmt.Println(o)
o.Set("pear", 9)
fmt.Println(o)
o.Delete("pear")
o.Set("pear", 1)
fmt.Println(o)
// A plain map: range gives the keys in an order that is not specified.
// Sorting is one way to get a stable order; insertion order is lost.
m := map[string]int{"pear": 4, "apple": 7, "fig": 2}
seen := []string{}
for k := range m {
seen = append(seen, k)
}
slices.Sort(seen)
fmt.Println(seen, len(m))
}
pear=4 apple=7 fig=2
pear=9 apple=7 fig=2
apple=7 fig=2 pear=1
[apple fig pear] 3
- Verdict: idiom. A Go map has no order, and a range loop gives the keys in an order that is not specified. The example keeps a slice of keys next to the map. Delete must also remove the key from the slice, which is linear.
use std::collections::HashMap;
// The standard library has no insertion-ordered map. This one keeps the entries
// in a Vec and an index from each key to its position, like the indexmap crate.
struct IndexMap {
entries: Vec<(String, i32)>,
index: HashMap<String, usize>,
}
impl IndexMap {
fn new() -> Self {
IndexMap { entries: Vec::new(), index: HashMap::new() }
}
fn insert(&mut self, k: &str, v: i32) {
match self.index.get(k) {
Some(&i) => self.entries[i].1 = v,
None => {
self.index.insert(k.to_string(), self.entries.len());
self.entries.push((k.to_string(), v));
}
}
}
fn get(&self, k: &str) -> Option<i32> {
self.index.get(k).map(|&i| self.entries[i].1)
}
// Fast remove: move the last entry into the hole. The order changes.
fn swap_remove(&mut self, k: &str) {
if let Some(i) = self.index.remove(k) {
self.entries.swap_remove(i);
if i < self.entries.len() {
let moved = self.entries[i].0.clone();
self.index.insert(moved, i);
}
}
}
// Slow remove: shift the later entries down. The order stays, but this is linear.
fn shift_remove(&mut self, k: &str) {
if let Some(i) = self.index.remove(k) {
self.entries.remove(i);
for (j, (key, _)) in self.entries.iter().enumerate().skip(i) {
self.index.insert(key.clone(), j);
}
}
}
fn keys(&self) -> Vec<&str> {
self.entries.iter().map(|(k, _)| k.as_str()).collect()
}
}
fn main() {
let mut m = IndexMap::new();
for (k, v) in [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5)] {
m.insert(k, v);
}
m.insert("a", 10);
println!("{:?} {:?}", m.keys(), m.get("a"));
let mut s = IndexMap { entries: m.entries.clone(), index: m.index.clone() };
m.swap_remove("b");
println!("{:?} {:?}", m.keys(), m.get("e"));
s.shift_remove("b");
println!("{:?} {:?}", s.keys(), s.get("e"));
// A HashMap iterates in an arbitrary order, so the output sorts the keys.
let h: HashMap<&str, i32> = [("pear", 4), ("apple", 7), ("fig", 2)].into_iter().collect();
let mut ks: Vec<_> = h.keys().copied().collect();
ks.sort();
println!("{:?}", ks);
}
["a", "b", "c", "d", "e"] Some(10)
["a", "e", "c", "d"] Some(5)
["a", "c", "d", "e"] Some(5)
["apple", "fig", "pear"]
- Verdict: idiom. The standard library has no insertion-ordered map, and HashMap iterates in an arbitrary order. The example keeps a Vec of entries and a HashMap from key to position, like the indexmap crate. swap_remove is constant time but changes the order, and shift_remove keeps the order but is linear.
Variations and related ideas
- Sorted order. An ordered map keeps the keys in sorted order, not in insertion order. It costs logarithmic time for each operation. An insertion-ordered map keeps the constant average time of a hash table.
- LRU caches. An access-order map is the usual base for a cache that drops the least recently used entry. Python
functools.lru_cacheand many web caches work this way. - Insertion-ordered sets. Java
LinkedHashSetand JavaScriptSetkeep insertion order for a set. In Python,dict.fromkeys(items)removes duplicates from a list and keeps the first order of the items. See remove duplicates from a list. - JSON objects. The JSON format does not require a parser to keep the order of the members of an object. Parsers that read into an insertion-ordered map, such as the Python
jsonmodule and JavaScriptJSON.parse, keep the order of the text, so a program that reads and writes a file keeps the order of its fields. See JSON. - Index access. Some ordered maps also let a program read the entry at a position, for example C#
OrderedDictionary<TKey,TValue>.GetAtand the indexmap crate. Pythondictand JavaLinkedHashMapdo not.
Pitfalls
- Relying on an order that is not promised. A C#
Dictionaryoften gives the keys in insertion order when no key was removed, but the documentation says the order is undefined8. A program that depends on the order can break after a delete or in another version. Go goes further and makes the order of a range loop differ from one loop to the next7. - Equality ignores the order. Two Python dicts with the same pairs in a different order are equal. Two
OrderedDictobjects are equal only when the order is also the same. In Java, aLinkedHashMapequals aHashMapwith the same pairs. - An update does not move the key. A program that wants the most recent key last must remove the key and add it again, or use an access-order map.
- Plain objects in JavaScript. An object puts keys such as
"10"and"2"before all other keys, in number order. Use aMapwhen the order of the keys matters. - Changes during a loop. Python raises
RuntimeErrorwhen a dict changes size during a loop over it, and Java iterators throwConcurrentModificationException. In an access-orderLinkedHashMap, even agetcounts as a change, because it moves the entry. - Deletes that change the order. A fast remove in an array-based map moves the last entry into the hole. The indexmap crate calls this
swap_remove. Use the slowershift_removeto keep the order.
Cost
| Operation | Hash table with a linked list (LinkedHashMap) |
Array of entries with an index (dict, indexmap) |
Map with a separate key list (Go idiom) |
|---|---|---|---|
| lookup | constant on average | constant on average | constant on average |
| insert a new key | constant on average | constant on average (amortized) | constant on average (amortized) |
| update a value | constant on average | constant on average | constant on average |
| delete, keep the order | constant on average | constant with a hole, or linear with a shift | linear |
| loop in insertion order | linear in the size | linear in the size and the holes | linear in the size |
| first and last key | constant | constant, after the holes are skipped | constant |
| entry at a position | linear | constant when there are no holes | constant |
| extra memory | two links for each entry | one index for each slot | one key for each entry |
Java says that the performance of LinkedHashMap "is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity."3 A loop over a plain hash table must visit the empty buckets too.
History
PHP arrays have kept insertion order from the start, and PHP calls its array "actually an ordered map"13. Java added LinkedHashMap in version 1.4 in 2002. The .NET Framework 2.0 had a non-generic OrderedDictionary. Ruby hashes keep insertion order since Ruby 1.9. Python added collections.OrderedDict in 2.7 and 3.1. In CPython 3.6, a new compact dict kept the order as a side effect, and Python 3.7 made the order part of the language4. JavaScript added Map with insertion order in ECMAScript 2015, and ECMAScript 2020 completed the rules for the key order of plain objects6. PowerShell 3.0 added [ordered]11, Java 21 added SequencedMap in 2023, and .NET 9 added the generic OrderedDictionary<TKey,TValue> in 2024.
References
- Associative array, Wikipedia, Ordered dictionary
- Built-in Types, The Python Standard Library, Mapping types, dict
- Class LinkedHashMap, Java SE 25 API, Description
- What's New In Python 3.7, Summary, release highlights
- collections, Container datatypes, The Python Standard Library, OrderedDict objects
- Map, MDN Web Docs, Description, Objects vs. Maps, Key Order
- Go maps in action, The Go Blog, Iteration order
- Dictionary<TKey,TValue> class, .NET API reference, Remarks
- Struct HashMap, The Rust Standard Library, keys, iter
- OrderedDictionary<TKey,TValue> class, .NET API reference, Definition
- about_Hash_Tables, PowerShell documentation, Long description; Syntax
- mutableMapOf, Kotlin Standard Library API, Description
- Arrays, PHP Manual, Introduction
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 C7HPNH Edit this page History Report an error Markdown