Conceptadvanced
Multimap
Also called multidict, multi-value map, map of lists, dictionary of lists, std::multimap, ILookup, Multimap.
A multimap is a map in which one key can have more than one value. Most languages build it as a map whose values are lists, and C++ and C# have types for it.
- Applies to
- core-languages
Idea
A map has one value for each key. A second put with the same key replaces the first value. Much real data has more than one value for a key: a student takes many courses, a word appears on many pages of a book, and a web form sends many values for one check box field. A multimap keeps all of them.
Wikipedia defines it as "a generalization of a map or associative array abstract data type in which more than one value may be associated with and returned for a given key"1. It gives the student example: "If a student is enrolled in three courses, there will be three associations containing the same key."1 The usual way to build one is also in the definition: "Often the multimap is implemented as a map with lists or sets as the map values."1
# A multimap can hold more than one value for a key.
# Here each student has a list of courses.
enrolled = {}
def add(student, course):
enrolled.setdefault(student, []).append(course)
add("ada", "math")
add("bob", "art")
add("ada", "physics")
add("ada", "music")
print(enrolled["ada"], enrolled["bob"])
print(enrolled.get("cy", []))
# The number of keys and the number of key-value pairs are different.
print(len(enrolled), sum(len(v) for v in enrolled.values()))
# The same data, seen as one pair for each value.
print([(s, c) for s, cs in enrolled.items() for c in cs])
['math', 'physics', 'music'] ['art']
[]
2 4
[('ada', 'math'), ('ada', 'physics'), ('ada', 'music'), ('bob', 'art')]
The map has two keys but four pairs. A student with no courses gives an empty list, not an error.
How it works
Two views of the same data. The Guava library describes two ways to see a multimap. It is "a collection of mappings from single keys to single values"2, such as a -> 1, a -> 2 and b -> 3, or it is "a mapping from unique keys to collections of values"2, such as a -> [1, 2] and b -> [3]. The first view counts pairs. The second view counts keys. Guava warns that its size method "returns the number of entries in the entire multimap, not the number of distinct keys"2.
A map of collections. Most programs build a multimap from a normal map whose values are lists or sets. To add a value, the program gets the list for the key, makes an empty list if the key is new, and appends the value. Each language has a short form for this step: setdefault or defaultdict in Python, computeIfAbsent in Java, entry().or_default() in Rust, and append on a missing key in Go. The Java Map documentation shows the step for "a multi-value map, Map<K,Collection>, supporting multiple values per key"3. To remove a value, the program removes it from the list, and then removes the key if the list is empty.
Lists or sets as values. A list keeps every value, in the order of the inserts, and it can hold the same value twice. A set keeps each value once for each key. Guava has both kinds: a ListMultimap and a SetMultimap. Choose by the question that the data must answer. A list of the orders of a customer can repeat a product. A set of the tags of a page cannot repeat a tag.
One container for all pairs. C++ std::multimap does not use a list for each key. It "is an associative container that contains a sorted list of key-value pairs, while permitting multiple entries with the same key"4. All pairs are in one tree. The pairs with equal keys are next to each other, and "The order of the key-value pairs whose keys compare equivalent is the order of insertion and does not change."4 The method equal_range returns the run of pairs for one key.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Standard library | |
| Java | Idiom | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Idiom | |
| TypeScript | Idiom | TypeScript uses the JavaScript idioms: a Map<K, V[]>, Map.groupBy, and URLSearchParams for query strings. No example file exists. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Idiom | A MutableMap<K, MutableList<V>> filled with getOrPut(key) { mutableListOf() }.add(v). groupBy builds a Map<K, List<V>> from a collection. No example file exists because kotlinc is not installed. |
| SQL | Native | A table with a key column that is not unique is a multimap. WHERE key = x returns all values of a key, and GROUP BY with an aggregate such as COUNT or STRING_AGG works on each key. |
| Bash | Idiom | Bash associative arrays hold one string for each key. A script joins the values of a key into one string with a separator, or keeps one array for each key. No example file exists. |
| PowerShell | Idiom | A hashtable whose values are lists, or Group-Object, which groups objects by a property. The .NET ToLookup method also works. 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 | idiom | a dict of lists with setdefault or collections.defaultdict(list) |
| JavaScript | idiom | a Map of arrays; Map.groupBy; URLSearchParams with getAll |
| TypeScript | idiom | the JavaScript idioms, typed as Map<K, V[]> |
| Java | idiom | Map<K, List<V>> with computeIfAbsent; Collectors.groupingBy; Guava Multimap |
| Kotlin | idiom | MutableMap<K, MutableList<V>> with getOrPut; groupBy |
| C# | stdlib | ILookup<TKey,TElement> from ToLookup, which cannot change; Dictionary<TKey, List<TValue>> |
| Go | idiom | map[K][]V; url.Values and http.Header are maps of string slices |
| Rust | idiom | HashMap<K, Vec<V>> with entry(k).or_default().push(v) |
| C | idiom | a sorted array of pairs, with a binary search for the first pair of a key |
| C++ | stdlib | std::multimap and std::unordered_multimap with equal_range and count |
| Bash | idiom | one string of joined values for each key, or one array for each key |
| PowerShell | idiom | a hashtable of lists, or Group-Object |
| SQL | native | a table whose key column is not unique; WHERE, GROUP BY |
| 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 |
C++ has two multimap types. Wikipedia: "The C++ standard library provides the std::multimap container for the sorted multimap using a self-balancing binary search tree"1, and C++ also has "the std::unordered_multimap for the unordered multimap implemented with a hash table"1. Search, insert and remove in std::multimap "have logarithmic complexity"4.
C# has a multimap in LINQ, but it is read-only. Lookup<TKey,TElement> "Represents a collection of keys each mapped to one or more values"5, and "Lookup<TKey,TElement> objects are immutable, that is, you cannot add or remove elements or keys from a Lookup<TKey,TElement> object after it has been created"5. A program that adds values over time uses a Dictionary of lists.
Python shows the defaultdict form in its documentation: "Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists"6. Query strings are a common multimap. For Python parse_qs, "The dictionary keys are the unique query variable names and the values are lists of values for each name."7 In JavaScript, the URLSearchParams method getAll "returns all the values associated with a given search parameter as an array"8.
The example files show these forms. Python uses defaultdict(list) and defaultdict(set), removes a key when its list is empty, and reads a query string with parse_qs. JavaScript uses a Map of arrays, Map.groupBy and URLSearchParams. Java uses computeIfAbsent, computeIfPresent and Collectors.groupingBy. C# uses ToLookup and a Dictionary of lists. Go appends to a missing key and reads url.Values. Rust uses entry().or_default() on a BTreeMap. C sorts an array of pairs and finds the run of each key. C++ uses std::multimap with equal_range, count and erase.
from collections import defaultdict
from urllib.parse import parse_qs
# defaultdict(list) makes the empty list for a new key.
pairs = [("yellow", 1), ("blue", 2), ("yellow", 3), ("blue", 4), ("red", 1)]
d = defaultdict(list)
for k, v in pairs:
d[k].append(v)
print(dict(d))
# Reading a missing key with [] adds it. Use get or in to only read.
print(d.get("green"), "green" in d)
_ = d["green"]
print("green" in d, d["green"])
# Remove one value. Remove the key too when its list becomes empty.
d["red"].remove(1)
if not d["red"]:
del d["red"]
print(sorted(d))
# A set as the value keeps each value once for each key.
tags = defaultdict(set)
for k, v in [("a", "x"), ("a", "x"), ("a", "y")]:
tags[k].add(v)
print(sorted(tags["a"]))
# A query string is a multimap: one name can have many values.
print(parse_qs("color=red&size=9&color=blue"))
{'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}
None False
True []
['blue', 'green', 'yellow']
['x', 'y']
{'color': ['red', 'blue'], 'size': ['9']}
- Verdict: idiom. A dict of lists, built with setdefault or collections.defaultdict(list). Reading a missing key of a defaultdict with [] adds it. A set as the value keeps each value once. urllib.parse.parse_qs reads a query string into a dict of lists.
#include <iostream>
#include <map>
#include <string>
int main() {
// std::multimap keeps the pairs sorted by key and allows equal keys.
std::multimap<std::string, int> m;
m.insert({"yellow", 1});
m.insert({"blue", 2});
m.insert({"yellow", 3});
m.insert({"blue", 4});
m.insert({"red", 1});
// equal_range gives all pairs for one key, in insertion order.
auto [first, last] = m.equal_range("yellow");
for (auto it = first; it != last; ++it) std::cout << it->second << " ";
std::cout << "count " << m.count("yellow") << " size " << m.size() << "\n";
// A multimap has no operator[], because a key has no single value.
// erase(key) removes every pair with that key.
std::cout << m.erase("blue") << " " << m.size() << "\n";
// To remove one pair, erase an iterator.
m.erase(m.find("yellow"));
for (const auto& [k, v] : m) std::cout << k << "=" << v << " ";
std::cout << "end\n";
}
1 3 count 2 size 5
2 3
red=1 yellow=3 end
- Verdict: stdlib. std::multimap and std::unordered_multimap allow equal keys. equal_range gives all values of a key, count counts them, and erase with a key removes them all. A multimap has no operator[].
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// computeIfAbsent makes the list for a new key and returns it.
Map<String, List<Integer>> m = new TreeMap<>();
m.computeIfAbsent("yellow", k -> new ArrayList<>()).add(1);
m.computeIfAbsent("blue", k -> new ArrayList<>()).add(2);
m.computeIfAbsent("yellow", k -> new ArrayList<>()).add(3);
System.out.println(m + " " + m.getOrDefault("red", List.of()));
// Remove one value, and remove the key when its list is empty.
m.computeIfPresent("blue", (k, list) -> {
list.remove(Integer.valueOf(2));
return list.isEmpty() ? null : list;
});
System.out.println(m);
// Collectors.groupingBy builds a multimap from a stream.
Map<Character, List<String>> byFirst = Stream.of("ant", "bee", "cat", "ape", "bat")
.collect(Collectors.groupingBy(w -> w.charAt(0), TreeMap::new, Collectors.toList()));
System.out.println(byFirst);
// The number of pairs is the sum of the list sizes.
int pairs = byFirst.values().stream().mapToInt(List::size).sum();
System.out.println(byFirst.size() + " " + pairs);
}
}
{blue=[2], yellow=[1, 3]} []
{yellow=[1, 3]}
{a=[ant, ape], b=[bee, bat], c=[cat]}
3 5
- Verdict: idiom. A Map<K, List> filled with computeIfAbsent, which the Map documentation shows for a multi-value map. computeIfPresent can remove a key when its list becomes empty. Collectors.groupingBy builds a multimap from a stream. Guava and Apache Commons Collections have Multimap types.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A multimap as a sorted array of pairs. Equal keys sit next to each other,
so all values of a key are one run that a binary search finds. */
struct pair {
const char *key;
int val;
int seq; /* insertion number, to keep equal keys in insertion order */
};
static int cmp(const void *a, const void *b) {
const struct pair *x = a, *y = b;
int c = strcmp(x->key, y->key);
return c != 0 ? c : x->seq - y->seq;
}
/* The first index whose key is >= k. */
static size_t lower(const struct pair *p, size_t n, const char *k) {
size_t lo = 0, hi = n;
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
if (strcmp(p[mid].key, k) < 0) lo = mid + 1; else hi = mid;
}
return lo;
}
static void show(const struct pair *p, size_t n, const char *k) {
size_t i = lower(p, n, k);
printf("%s:", k);
for (; i < n && strcmp(p[i].key, k) == 0; i++) printf(" %d", p[i].val);
printf("\n");
}
int main(void) {
struct pair p[] = {
{"yellow", 1, 0}, {"blue", 2, 1}, {"yellow", 3, 2}, {"blue", 4, 3}, {"red", 1, 4},
};
size_t n = sizeof p / sizeof p[0];
qsort(p, n, sizeof p[0], cmp);
show(p, n, "blue");
show(p, n, "yellow");
show(p, n, "green");
/* Count the distinct keys: a key starts a run when it differs from the one before. */
size_t keys = 0;
for (size_t i = 0; i < n; i++)
if (i == 0 || strcmp(p[i].key, p[i - 1].key) != 0) keys++;
printf("%zu keys, %zu pairs\n", keys, n);
return 0;
}
blue: 2 4
yellow: 1 3
green:
3 keys, 5 pairs
- Verdict: idiom. C has no maps. The example sorts an array of pairs by key, with an insertion number to keep equal keys in order. A binary search finds the first pair of a key, and the values of the key are the run of pairs from there.
// ToLookup builds a read-only multimap. A missing key gives an empty sequence.
string[] words = ["ant", "bee", "cat", "ape", "bat"];
ILookup<char, string> byFirst = words.ToLookup(w => w[0]);
Console.WriteLine(string.Join(",", byFirst['a']) + " " + byFirst['z'].Count() + " " + byFirst.Contains('z'));
Console.WriteLine(string.Join(" ", byFirst.Select(g => $"{g.Key}:{g.Count()}")));
// A Dictionary of Lists is the usual multimap that can change.
var m = new Dictionary<string, List<int>>();
void Add(string k, int v)
{
if (!m.TryGetValue(k, out var list))
{
list = [];
m[k] = list;
}
list.Add(v);
}
Add("yellow", 1);
Add("blue", 2);
Add("yellow", 3);
Console.WriteLine(string.Join(",", m["yellow"]) + " " + m.ContainsKey("red"));
// Remove one value, and the key when its list is empty.
m["blue"].Remove(2);
if (m["blue"].Count == 0) m.Remove("blue");
Console.WriteLine(string.Join(" ", m.Keys) + " " + m.Values.Sum(l => l.Count));
ant,ape 0 False
a:2 b:2 c:1
1,3 False
yellow 2
- Verdict: stdlib. ToLookup builds an ILookup<TKey,TElement>, a multimap that cannot change, where a missing key gives an empty sequence. A Dictionary<TKey, List> is the multimap that can change.
// A Map whose values are arrays.
const m = new Map();
function add(k, v) {
if (!m.has(k)) m.set(k, []);
m.get(k).push(v);
}
add("yellow", 1);
add("blue", 2);
add("yellow", 3);
console.log(m.get("yellow"), m.get("red") ?? []);
// Map.groupBy (ES2024) builds a multimap from a list in one call.
const words = ["ant", "bee", "cat", "ape", "bat"];
const byFirst = Map.groupBy(words, (w) => w[0]);
console.log([...byFirst].map(([k, v]) => `${k}:${v.join(",")}`).join(" "));
// URLSearchParams is a multimap of strings. get returns the first value.
const q = new URLSearchParams("color=red&size=9&color=blue");
console.log(q.get("color"), q.getAll("color"), q.getAll("shape"));
q.append("color", "green");
console.log(q.toString());
// Object.fromEntries keeps only the last value for a repeated key.
console.log(Object.fromEntries(q));
[ 1, 3 ] []
a:ant,ape b:bee,bat c:cat
red [ 'red', 'blue' ] []
color=red&size=9&color=blue&color=green
{ color: 'green', size: '9' }
- Verdict: idiom. A Map whose values are arrays. Map.groupBy from ES2024 builds one from a list. URLSearchParams is a multimap of strings, with get for the first value and getAll for all values. Object.fromEntries keeps only the last value of a repeated key.
package main
import (
"fmt"
"net/url"
"slices"
)
func main() {
// A map of slices. append works on the nil slice of a missing key.
m := map[string][]int{}
m["yellow"] = append(m["yellow"], 1)
m["blue"] = append(m["blue"], 2)
m["yellow"] = append(m["yellow"], 3)
fmt.Println(m["yellow"], m["red"], len(m["red"]))
// Remove one value. Delete the key when its slice is empty.
m["blue"] = slices.DeleteFunc(m["blue"], func(x int) bool { return x == 2 })
if len(m["blue"]) == 0 {
delete(m, "blue")
}
_, ok := m["blue"]
fmt.Println(len(m), ok)
// url.Values is a map[string][]string. Get returns the first value.
q, err := url.ParseQuery("color=red&size=9&color=blue")
if err != nil {
panic(err)
}
fmt.Println(q.Get("color"), q["color"], q.Get("shape") == "")
q.Add("color", "green")
fmt.Println(q.Encode())
}
[1 3] [] 0
1 false
red [red blue] true
color=red&color=blue&color=green&size=9
- Verdict: idiom. A map[K][]V. append works on the nil slice of a missing key, so no check is needed. url.Values and http.Header in the standard library are maps of string slices with Get for the first value.
use std::collections::BTreeMap;
fn main() {
// entry().or_default() makes an empty Vec for a new key.
let mut m: BTreeMap<&str, Vec<i32>> = BTreeMap::new();
for (k, v) in [("yellow", 1), ("blue", 2), ("yellow", 3), ("blue", 4), ("red", 1)] {
m.entry(k).or_default().push(v);
}
println!("{:?}", m);
println!("{:?}", m.get("green").map(|v| v.len()).unwrap_or(0));
// Remove one value. Remove the key when its Vec is empty.
if let Some(v) = m.get_mut("red") {
v.retain(|&x| x != 1);
if v.is_empty() {
m.remove("red");
}
}
let pairs: usize = m.values().map(Vec::len).sum();
println!("{} {}", m.len(), pairs);
// Each key and each value, as flat pairs.
let flat: Vec<(&str, i32)> = m.iter().flat_map(|(k, vs)| vs.iter().map(move |v| (*k, *v))).collect();
println!("{:?}", flat);
}
{"blue": [2, 4], "red": [1], "yellow": [1, 3]}
0
2 4
[("blue", 2), ("blue", 4), ("yellow", 1), ("yellow", 3)]
- Verdict: idiom. A HashMap or BTreeMap of Vec values, filled with entry(k).or_default().push(v). retain removes values, and the program removes a key when its Vec becomes empty.
Variations and related ideas
- Grouping. Building a multimap from a list is grouping: group items by a key.
itertools.groupby,Collectors.groupingBy,GroupByin LINQ andGROUP BYin SQL do it. - Multisets. A multiset keeps only the number of times each item appears. A multimap whose values are all the same is a multiset of keys.
- Inverse index. A multimap from each word to the documents that contain it is an inverted index, the base of a search engine. The index of a book is the same idea.
- Bimaps. A bimap holds a map and its inverse, so a program can look up a key by its value. Guava has
BiMap. Unlike a multimap, a bimap does not allow two keys to have the same value. - Graphs. A map from each node to the list of its neighbors is an adjacency list. Guava notes that a map of sets "is a typical way to represent an unlabeled directed graph"2.
- HTTP headers. A header name can appear more than once in a request, so header types in Go, Java and .NET hold a list of values for each name.
Pitfalls
- Keys with empty lists. A program that removes the last value of a key but keeps the key gets a key with an empty list. Then a test such as
key in mapsays yes, but there are no values. Remove the key when its list becomes empty. - Reading adds a key. In Python,
d[k]on adefaultdictaddskwith an empty list. Used.get(k)ork in dwhen the program must only read. - The first value or all values.
URLSearchParams.get, Gourl.Values.Getandhttp.Header.Getreturn only the first value of a name. A program that must see all values usesgetAllor the slice. Converting a multimap to a plain map, for example withObject.fromEntries, keeps only one value for each key. - Size. The number of keys and the number of pairs are different numbers. Check which one a method returns.
- Shared lists. In Python,
dict.fromkeys(keys, [])gives every key the same list, so an append to one key changes them all. Usedefaultdict(list)or a new list for each key. - No index operator in C++.
std::multimaphas nooperator[], anderase(key)removes all pairs with that key. To remove one pair, erase an iterator.
Cost
| Operation | Hash map of lists | Tree map of lists | std::multimap (one tree) |
|---|---|---|---|
| add a value | constant on average | logarithmic in the keys | logarithmic in the pairs |
| all values of a key | constant on average to find, then k | logarithmic in the keys, then k | logarithmic in the pairs, then k |
| count values of a key | constant on average | logarithmic in the keys | logarithmic + k |
| remove one value | find, then linear in the list | find, then linear in the list | logarithmic, with an iterator constant |
| remove a key | constant on average | logarithmic | logarithmic + k |
| loop over all pairs | linear | linear, in key order | linear, in key order |
| memory | one list for each key | one list for each key | one tree node for each pair |
Here k is the number of values of one key. A map of lists stores each key once, so it uses less memory when keys have many values. One tree for all pairs, as in std::multimap, stores the key in each pair.
History
Multimaps came into wide use with the C++ Standard Template Library, which had multimap and multiset in its first version and entered the C++ standard in 1998. The hash form std::unordered_multimap came with C++111, and C++11 also fixed the order of the pairs with equal keys as the order of insertion4. Java never added a multimap to its standard library. Apache Commons Collections and Google Guava filled the gap, and Java 8 in 2014 added computeIfAbsent and Collectors.groupingBy, which make the map of lists short to write. C# added ToLookup with LINQ in 2007, and JavaScript added Map.groupBy in ECMAScript 2024.
References
- Multimap, Wikipedia, Introduction; Examples; Language support
- New Collection Types Explained, Guava wiki, Multimap
- Interface Map, Java SE 25 API, computeIfAbsent
- std::multimap, cppreference.com, Description
- Lookup<TKey,TElement> class, .NET API reference, Remarks
- collections, Container datatypes, The Python Standard Library, defaultdict examples
- urllib.parse, Parse URLs into components, The Python Standard Library, parse_qs
- URLSearchParams getAll() method, MDN Web Docs, Description; Return value
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 TVB6S4 Edit this page History Report an error Markdown