Programming Search⌘K

Taskintro

Merge two maps

Also called combine two dictionaries, merge dictionaries, update a map from another map, union of two maps.

Make a new map with the entries of two maps, where the value of the second map wins for a key in both, and keep the two maps unchanged.

Task

Merge two maps into a new map. The function merge_maps(base, override) returns the entries of both maps. For a key that is in both maps, the value of override wins. The function does not change base or override. It returns the entries as pairs (key, value), in ascending order of the key by its bytes. For example, merge_maps({"apple": 3, "pear": 5}, {"pear": 6, "fig": 2}) is [("apple", 3), ("fig", 2), ("pear", 6)].

Each key has 1 or more ASCII letters. Each value fits in a signed 32-bit integer. Either map can be empty.

Solutions

Language Copy the base map Add the override map
Python base | override makes a new dict (one operator)
JavaScript, TypeScript new Map([...base, ...override]) (one constructor)
Java new TreeMap<>(base) merged.putAll(override)
C# new Dictionary<string, int>(baseMap) merged[key] = value for each entry
Go maps.Clone(base) maps.Copy(merged, override)
Rust base.clone() merged.extend(...)
C (not needed) one pass over both sorted arrays
C++ std::map<std::string, int> merged(base.begin(), base.end()) merged.insert_or_assign(key, value)
Bash local -A merged=() merged[key]=value for each pair, base first
  • Which value wins. Each solution copies the base map, then puts each entry of the override map in the copy with an operation that replaces a value. In Python, base | override gives "a new dictionary with the merged keys and values of d and other"1, and "The values of other take priority when d and other share keys."1 In JavaScript, for an object spread, "the property takes the last value assigned"2. In Go, for maps.Copy, "When a key in src is already present in dst, the value in dst will be overwritten by the value associated with the key in src."3 Rust extend "Inserts all new key-values from the iterator and replaces values with existing keys with new values returned from the iterator."4
  • The inputs do not change. A copy keeps the base map as it is. A solution that puts the entries of override straight into base is faster, but it changes the map of the caller.
  • The order. The Java, C++ and C solutions build a sorted map. The others sort the entries at the end, as in Iterate over a map.
  • C. A map is an array of entries in key order, as in Create a map. One pass over both arrays, like the merge step of a merge sort, gives the result in key order. For a key in both arrays, the pass takes the entry of override and skips the entry of base.
  • Bash. The function takes the base pairs, then --, then the override pairs, as KEY=VALUE arguments. A later assignment to a key replaces the earlier value, so the override pairs win.
  • A deep merge. When the values are maps too, a merge replaces the inner map of the base with the inner map of the override. A deep merge merges the two inner maps, and so on down. The standard libraries of these languages have no deep merge. Also, a copy of a map copies one level: in JavaScript, "no native operation in JavaScript does a deep clone."2

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty-base, empty-override and both-empty: an empty map adds nothing.
  • same-keys: when the two maps have the same keys, the result has the values of override.
  • zero-wins: the override value 0 wins over the base value 5. A test such as override.get(key) or base[key] in Python takes 5, because 0 is false.
  • case: a and A are two different keys, so both stay.

Pitfalls

  • Python update changes the dict and returns None. update does this: "Update the dictionary with the key/value pairs from mapping or iterable and kwargs, overwriting existing keys. Return None."1 Thus merged = base.update(override) gives None and changes base. Use base | override for a new dict:
base = {"apple": 3, "pear": 5}
over = {"pear": 6, "fig": 2}
merged = base.update(over)
print(merged, base)
base = {"apple": 3, "pear": 5}
print(base | over, base)
Output
None {'apple': 3, 'pear': 6, 'fig': 2}
{'apple': 3, 'pear': 6, 'fig': 2} {'apple': 3, 'pear': 5}
  • JavaScript object spread of a Map gives an empty object, and a spread is shallow. An object spread copies the own properties of a value, and a Map keeps its entries outside its properties. Spread the entries into a new Map. Also, "Spread syntax effectively goes one level deep while copying an array."2 The same is true for objects, so the copy b shares the inner object with a:
const base = new Map([["apple", 3]]);
console.log({ ...base });
const over = new Map([["pear", 6]]);
console.log(new Map([...base, ...over]));
const a = { size: { n: 1 } };
const b = { ...a };
b.size.n = 2;
console.log(a.size.n);
Output
{}
Map(2) { 'apple' => 3, 'pear' => 6 }
2
  • Java Collectors.toMap throws on a key in both maps. "If the mapped keys contain duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed."5 Give a merge function as the third argument. (a, b) -> b takes the later value:
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) {
    Map<String, Integer> base = Map.of("apple", 3, "pear", 5);
    Map<String, Integer> over = Map.of("pear", 6);
    try {
      Stream.concat(base.entrySet().stream(), over.entrySet().stream())
          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    } catch (IllegalStateException e) {
      System.out.println(e.getClass().getSimpleName());
    }
    Map<String, Integer> merged = Stream.concat(base.entrySet().stream(), over.entrySet().stream())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b, TreeMap::new));
    System.out.println(merged);
  }
}
Output
IllegalStateException
{apple=3, pear=6}
  • C# Concat then ToDictionary throws on a key in both maps. ToDictionary throws an ArgumentException when the "keySelector produces duplicate keys for two elements."6 Copy the base dictionary, then set each entry of the override with the indexer:
using System;
using System.Collections.Generic;
using System.Linq;

var baseMap = new Dictionary<string, int> { ["apple"] = 3, ["pear"] = 5 };
var over = new Dictionary<string, int> { ["pear"] = 6 };
try
{
    _ = baseMap.Concat(over).ToDictionary(p => p.Key, p => p.Value);
}
catch (ArgumentException e)
{
    Console.WriteLine(e.GetType().Name);
}
var merged = new Dictionary<string, int>(baseMap);
foreach (var (key, value) in over)
{
    merged[key] = value;
}
Console.WriteLine(string.Join(" ", merged.OrderBy(p => p.Key, StringComparer.Ordinal).Select(p => p.Key + "=" + p.Value)));
Output
ArgumentException
apple=3 pear=6
  • Go an assignment of a map does not copy it. "Map types are reference types, like pointers or slices"7. After merged := base, both names refer to one map, so maps.Copy(merged, ...) also changes base. Copy the map with maps.Clone first:
package main

import (
	"fmt"
	"maps"
)

func main() {
	base := map[string]int{"apple": 3, "pear": 5}
	merged := base
	maps.Copy(merged, map[string]int{"pear": 6})
	fmt.Println(base)
	base = map[string]int{"apple": 3, "pear": 5}
	merged = maps.Clone(base)
	maps.Copy(merged, map[string]int{"pear": 6})
	fmt.Println(base, merged)
}
Output
map[apple:3 pear:6]
map[apple:3 pear:5] map[apple:3 pear:6]
  • Rust extend lets the new value win. extend replaces the value of a key that is there4. To keep the value of the base, use the entry API: or_insert "Ensures a value is in the entry by inserting the default if empty"8, so it does not touch a key that is there:
use std::collections::{BTreeMap, HashMap};

fn main() {
    let base = HashMap::from([("apple", 3), ("pear", 5)]);
    let over = HashMap::from([("pear", 6), ("fig", 2)]);
    let mut a = base.clone();
    a.extend(over.clone());
    println!("{:?}", a.into_iter().collect::<BTreeMap<_, _>>());
    let mut b = base.clone();
    for (k, v) in over {
        b.entry(k).or_insert(v);
    }
    println!("{:?}", b.into_iter().collect::<BTreeMap<_, _>>());
}
Output
{"apple": 3, "fig": 2, "pear": 6}
{"apple": 3, "fig": 2, "pear": 5}
  • C++ merge keeps the old value and leaves the other in the source. std::map::merge tries to take "each element in source and insert it into *this"9. "If there is an element in *this with key equivalent to the key of an element from source, then that element is not extracted from source."9 insert also keeps the value that is there. Use insert_or_assign to let the new value win:
#include <iostream>
#include <map>
#include <string>

static void print(const std::map<std::string, int> &m) {
    const char *sep = "";
    for (const auto &[key, value] : m) {
        std::cout << sep << key << '=' << value;
        sep = " ";
    }
    std::cout << '\n';
}

int main() {
    std::map<std::string, int> base{{"apple", 3}, {"pear", 5}};
    std::map<std::string, int> over{{"pear", 6}, {"fig", 2}};
    base.merge(over);
    print(base);
    print(over);
}
Output
apple=3 fig=2 pear=5
pear=6
  • C == compares the addresses of two keys, not the text. The merge must find equal keys, and strcmp "Compares two null-terminated byte strings lexicographically."10 Two strings with the same text in two arrays have two addresses, so == gives 0:
#include <stdio.h>
#include <string.h>

int main(void) {
    char a[] = "pear";
    char b[] = "pear";
    const char *x = a;
    const char *y = b;
    printf("%d %d\n", x == y, strcmp(x, y) == 0);
    return 0;
}
Output
0 1
  • Bash a copy of the values loses the keys. ${name[@]} gives the values, and the keys come from ${!name[@]}: "It is possible to obtain the keys (indices) of an array as well as the values."11 A copy into a new array gets the values with the indices 0, 1 and so on. Copy each key with its value:
f() {
  local -A base=([apple]=3)
  local -a copy=("${base[@]}")
  echo "${!copy[*]} ${copy[0]}"
  local -A merged=()
  local key
  for key in "${!base[@]}"; do
    merged[$key]=${base[$key]}
  done
  echo "${!merged[*]} ${merged[apple]}"
}
f
Output
0 3
apple 3

Code

The build runs the native tests of each language in a pinned toolchain.

merge_maps.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/merge-two-maps/.


def merge_maps(base: dict[str, int], override: dict[str, int]) -> list[tuple[str, int]]:
    """Return the entries of both dicts in key order; the value of override wins."""
    # | makes a new dict. The values of the right operand win.
    merged = base | override
    return sorted(merged.items())
test_merge_maps.py 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/merge-two-maps/.

import pytest

from merge_maps import merge_maps

CASES = {
    "prices": ({"apple": 3, "pear": 5}, {"pear": 6, "fig": 2}, [("apple", 3), ("fig", 2), ("pear", 6)]),
    "disjoint": ({"a": 1}, {"b": 2}, [("a", 1), ("b", 2)]),
    "empty-base": ({}, {"a": 1}, [("a", 1)]),
    "empty-override": ({"a": 1}, {}, [("a", 1)]),
    "both-empty": ({}, {}, []),
    "same-keys": ({"a": 1, "b": 2}, {"a": 9, "b": 8}, [("a", 9), ("b", 8)]),
    "zero-wins": ({"a": 5}, {"a": 0}, [("a", 0)]),
    "case": ({"a": 1}, {"A": 2}, [("A", 2), ("a", 1)]),
}


@pytest.mark.parametrize("name", CASES)
def test_merge_maps(name):
    base, override, want = CASES[name]
    before = (dict(base), dict(override))
    assert merge_maps(base, override) == want
    assert (base, override) == before
merge_maps.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

#include "merge_maps.hpp"

#include <map>

std::vector<std::pair<std::string, int>> merge_maps(const std::unordered_map<std::string, int> &base, const std::unordered_map<std::string, int> &over) {
    // A std::map gives its entries in key order.
    std::map<std::string, int> merged(base.begin(), base.end());
    for (const auto &[key, value] : over) {
        // insert and merge keep the value that is there. insert_or_assign replaces it.
        merged.insert_or_assign(key, value);
    }
    return {merged.begin(), merged.end()};
}
merge_maps.hpp 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

#pragma once

#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

// merge_maps returns the entries of both maps in ascending order of the key.
// For a key in both maps, the value of over wins.
std::vector<std::pair<std::string, int>> merge_maps(const std::unordered_map<std::string, int> &base, const std::unordered_map<std::string, int> &over);
test_merge_maps.cpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

#include "merge_maps.hpp"

#include <iostream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>

static int failures = 0;

using Map = std::unordered_map<std::string, int>;
using Pairs = std::vector<std::pair<std::string, int>>;

static void check(std::string_view name, const Map &base, const Map &over, const Pairs &want) {
    if (merge_maps(base, over) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("prices", Map{{"apple", 3}, {"pear", 5}}, Map{{"pear", 6}, {"fig", 2}}, Pairs{{"apple", 3}, {"fig", 2}, {"pear", 6}});
    check("disjoint", Map{{"a", 1}}, Map{{"b", 2}}, Pairs{{"a", 1}, {"b", 2}});
    check("empty-base", Map{}, Map{{"a", 1}}, Pairs{{"a", 1}});
    check("empty-override", Map{{"a", 1}}, Map{}, Pairs{{"a", 1}});
    check("both-empty", Map{}, Map{}, Pairs{});
    check("same-keys", Map{{"a", 1}, {"b", 2}}, Map{{"a", 9}, {"b", 8}}, Pairs{{"a", 9}, {"b", 8}});
    check("zero-wins", Map{{"a", 5}}, Map{{"a", 0}}, Pairs{{"a", 0}});
    check("case", Map{{"a", 1}}, Map{{"A", 2}}, Pairs{{"A", 2}, {"a", 1}});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
MergeMaps.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

final class MergeMaps {
  private MergeMaps() {}

  /** Returns the entries of both maps in key order; the value of override wins. */
  static List<Map.Entry<String, Integer>> mergeMaps(Map<String, Integer> base, Map<String, Integer> override) {
    // The copy keeps base as it is. putAll replaces the values of keys that are there.
    Map<String, Integer> merged = new TreeMap<>(base);
    merged.putAll(override);
    return merged.entrySet().stream()
        .map(e -> Map.entry(e.getKey(), e.getValue()))
        .toList();
  }
}
MergeMapsTest.java 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class MergeMapsTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("prices", Map.of("apple", 3, "pear", 5), Map.of("pear", 6, "fig", 2), List.of(Map.entry("apple", 3), Map.entry("fig", 2), Map.entry("pear", 6))),
        Arguments.of("disjoint", Map.of("a", 1), Map.of("b", 2), List.of(Map.entry("a", 1), Map.entry("b", 2))),
        Arguments.of("empty-base", Map.of(), Map.of("a", 1), List.of(Map.entry("a", 1))),
        Arguments.of("empty-override", Map.of("a", 1), Map.of(), List.of(Map.entry("a", 1))),
        Arguments.of("both-empty", Map.of(), Map.of(), List.of()),
        Arguments.of("same-keys", Map.of("a", 1, "b", 2), Map.of("a", 9, "b", 8), List.of(Map.entry("a", 9), Map.entry("b", 8))),
        Arguments.of("zero-wins", Map.of("a", 5), Map.of("a", 0), List.of(Map.entry("a", 0))),
        Arguments.of("case", Map.of("a", 1), Map.of("A", 2), List.of(Map.entry("A", 2), Map.entry("a", 1))));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void mergeMaps(String name, Map<String, Integer> base, Map<String, Integer> override, List<Map.Entry<String, Integer>> want) {
    // HashMap copies can change, so the test also checks that the function does not change them.
    var b = new HashMap<>(base);
    var o = new HashMap<>(override);
    assertEquals(want, MergeMaps.mergeMaps(b, o));
    assertEquals(base, b);
    assertEquals(override, o);
  }
}
merge_maps.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

#include "merge_maps.h"

#include <string.h>

size_t merge_maps(const struct entry *base, size_t nb, const struct entry *over, size_t no, struct entry *out) {
    // Both arrays are in key order, so one pass over both, like the merge step
    // of a merge sort, gives the result in key order.
    size_t i = 0;
    size_t j = 0;
    size_t k = 0;
    while (i < nb || j < no) {
        int c;
        if (i == nb) {
            c = 1;
        } else if (j == no) {
            c = -1;
        } else {
            c = strcmp(base[i].key, over[j].key);
        }
        if (c < 0) {
            out[k++] = base[i++];
        } else if (c > 0) {
            out[k++] = over[j++];
        } else {
            // The same key in both: take the entry of over, and skip both.
            out[k++] = over[j++];
            i++;
        }
    }
    return k;
}
merge_maps.h 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

#ifndef MERGE_MAPS_H
#define MERGE_MAPS_H

#include <stddef.h>

// An entry of a map. A map is an array of entries in ascending order of the
// key, with no key two times.
struct entry {
    const char *key;
    int value;
};

// merge_maps writes the entries of the maps base (nb entries) and over (no
// entries) to out, in ascending order of the key. For a key in both maps, the
// entry of over wins. out must have room for nb + no entries. It returns the
// number of entries.
size_t merge_maps(const struct entry *base, size_t nb, const struct entry *over, size_t no, struct entry *out);

#endif
test_merge_maps.c 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

#include "merge_maps.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// An empty map has a dummy entry in it, because C has no empty array. The
// counts give the real lengths.
#define CHECK(name, nb, b, no, o, k, ...)                                      \
    do {                                                                       \
        const struct entry base[] = b;                                         \
        const struct entry over[] = o;                                         \
        const struct entry want[] = {__VA_ARGS__};                             \
        struct entry out[sizeof base / sizeof base[0] + sizeof over / sizeof over[0]]; \
        const size_t want_k = k;                                               \
        size_t got = merge_maps(base, nb, over, no, out);                      \
        int ok = got == want_k;                                                \
        for (size_t i = 0; ok && i < want_k; i++) {                            \
            ok = strcmp(out[i].key, want[i].key) == 0 &&                       \
                 out[i].value == want[i].value;                                \
        }                                                                      \
        if (!ok) {                                                             \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("prices", 2, L({"apple", 3}, {"pear", 5}), 2, L({"fig", 2}, {"pear", 6}), 3, {"apple", 3}, {"fig", 2}, {"pear", 6});
    CHECK("disjoint", 1, L({"a", 1}), 1, L({"b", 2}), 2, {"a", 1}, {"b", 2});
    CHECK("empty-base", 0, L({"", 0}), 1, L({"a", 1}), 1, {"a", 1});
    CHECK("empty-override", 1, L({"a", 1}), 0, L({"", 0}), 1, {"a", 1});
    CHECK("both-empty", 0, L({"", 0}), 0, L({"", 0}), 0, {NULL, 0});
    CHECK("same-keys", 2, L({"a", 1}, {"b", 2}), 2, L({"a", 9}, {"b", 8}), 2, {"a", 9}, {"b", 8});
    CHECK("zero-wins", 1, L({"a", 5}), 1, L({"a", 0}), 1, {"a", 0});
    CHECK("case", 1, L({"a", 1}), 1, L({"A", 2}), 2, {"A", 2}, {"a", 1});
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
MergeMaps.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

using System;
using System.Collections.Generic;
using System.Linq;

public static class MergeMaps
{
    // Merge returns the entries of both dictionaries in key order; the value of over wins.
    public static (string Key, int Value)[] Merge(Dictionary<string, int> baseMap, Dictionary<string, int> over)
    {
        // The copy keeps baseMap as it is. The indexer replaces the value of a key that is there.
        var merged = new Dictionary<string, int>(baseMap);
        foreach (var (key, value) in over)
        {
            merged[key] = value;
        }
        return merged.OrderBy(p => p.Key, StringComparer.Ordinal).Select(p => (p.Key, p.Value)).ToArray();
    }
}
MergeMapsTests.cs 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

using System.Collections.Generic;
using System.Linq;
using Xunit;

public sealed class MergeMapsTests
{
    public static TheoryData<string, string[], int[], string[], int[], string[], int[]> Cases => new()
    {
        { "prices", new string[] { "apple", "pear" }, new int[] { 3, 5 }, new string[] { "pear", "fig" }, new int[] { 6, 2 }, new string[] { "apple", "fig", "pear" }, new int[] { 3, 2, 6 } },
        { "disjoint", new string[] { "a" }, new int[] { 1 }, new string[] { "b" }, new int[] { 2 }, new string[] { "a", "b" }, new int[] { 1, 2 } },
        { "empty-base", new string[0], new int[0], new string[] { "a" }, new int[] { 1 }, new string[] { "a" }, new int[] { 1 } },
        { "empty-override", new string[] { "a" }, new int[] { 1 }, new string[0], new int[0], new string[] { "a" }, new int[] { 1 } },
        { "both-empty", new string[0], new int[0], new string[0], new int[0], new string[0], new int[0] },
        { "same-keys", new string[] { "a", "b" }, new int[] { 1, 2 }, new string[] { "a", "b" }, new int[] { 9, 8 }, new string[] { "a", "b" }, new int[] { 9, 8 } },
        { "zero-wins", new string[] { "a" }, new int[] { 5 }, new string[] { "a" }, new int[] { 0 }, new string[] { "a" }, new int[] { 0 } },
        { "case", new string[] { "a" }, new int[] { 1 }, new string[] { "A" }, new int[] { 2 }, new string[] { "A", "a" }, new int[] { 2, 1 } },
    };

    private static Dictionary<string, int> Map(string[] keys, int[] values) => keys.Zip(values).ToDictionary(p => p.First, p => p.Second);

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, string[] baseKeys, int[] baseValues, string[] overKeys, int[] overValues, string[] wantKeys, int[] wantValues)
    {
        Assert.NotNull(name);
        var baseMap = Map(baseKeys, baseValues);
        var over = Map(overKeys, overValues);
        var got = MergeMaps.Merge(baseMap, over);
        Assert.Equal(wantKeys, got.Select(p => p.Key));
        Assert.Equal(wantValues, got.Select(p => p.Value));
        Assert.Equal(Map(baseKeys, baseValues), baseMap);
        Assert.Equal(Map(overKeys, overValues), over);
    }
}
merge_maps.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

/**
 * @param {Map<string, number>} base
 * @param {Map<string, number>} override
 * @returns {[string, number][]}
 */
export function mergeMaps(base, override) {
  // The entries of override come later, so their values win.
  const merged = new Map([...base, ...override]);
  return [...merged].sort((p, q) => (p[0] < q[0] ? -1 : p[0] > q[0] ? 1 : 0));
}
merge_maps.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { mergeMaps } from "./merge_maps.js";

const cases = [
  ["prices", new Map([["apple", 3], ["pear", 5]]), new Map([["pear", 6], ["fig", 2]]), [["apple", 3], ["fig", 2], ["pear", 6]]],
  ["disjoint", new Map([["a", 1]]), new Map([["b", 2]]), [["a", 1], ["b", 2]]],
  ["empty-base", new Map(), new Map([["a", 1]]), [["a", 1]]],
  ["empty-override", new Map([["a", 1]]), new Map(), [["a", 1]]],
  ["both-empty", new Map(), new Map(), []],
  ["same-keys", new Map([["a", 1], ["b", 2]]), new Map([["a", 9], ["b", 8]]), [["a", 9], ["b", 8]]],
  ["zero-wins", new Map([["a", 5]]), new Map([["a", 0]]), [["a", 0]]],
  ["case", new Map([["a", 1]]), new Map([["A", 2]]), [["A", 2], ["a", 1]]],
];

for (const [name, base, override, want] of cases) {
  test(name, () => {
    const before = [[...base], [...override]];
    assert.deepEqual(mergeMaps(base, override), want);
    assert.deepEqual([[...base], [...override]], before);
  });
}
merge_maps.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

export function mergeMaps(base: ReadonlyMap<string, number>, override: ReadonlyMap<string, number>): [string, number][] {
  // The entries of override come later, so their values win.
  const merged = new Map([...base, ...override]);
  return [...merged].sort((p, q) => (p[0] < q[0] ? -1 : p[0] > q[0] ? 1 : 0));
}
merge_maps.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { mergeMaps } from "./merge_maps.ts";

const cases: [string, Map<string, number>, Map<string, number>, [string, number][]][] = [
  ["prices", new Map([["apple", 3], ["pear", 5]]), new Map([["pear", 6], ["fig", 2]]), [["apple", 3], ["fig", 2], ["pear", 6]]],
  ["disjoint", new Map([["a", 1]]), new Map([["b", 2]]), [["a", 1], ["b", 2]]],
  ["empty-base", new Map<string, number>(), new Map([["a", 1]]), [["a", 1]]],
  ["empty-override", new Map([["a", 1]]), new Map<string, number>(), [["a", 1]]],
  ["both-empty", new Map<string, number>(), new Map<string, number>(), []],
  ["same-keys", new Map([["a", 1], ["b", 2]]), new Map([["a", 9], ["b", 8]]), [["a", 9], ["b", 8]]],
  ["zero-wins", new Map([["a", 5]]), new Map([["a", 0]]), [["a", 0]]],
  ["case", new Map([["a", 1]]), new Map([["A", 2]]), [["A", 2], ["a", 1]]],
];

for (const [name, base, override, want] of cases) {
  test(name, () => {
    const before = [[...base], [...override]];
    assert.deepEqual(mergeMaps(base, override), want);
    assert.deepEqual([[...base], [...override]], before);
  });
}
merge_maps.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

// Package mergemaps merges two maps into a new map.
package mergemaps

import (
	"maps"
	"slices"
)

// Pair is one entry of a map.
type Pair struct {
	Key   string
	Value int
}

// MergeMaps returns the entries of both maps in ascending order of the key.
// For a key in both maps, the value of override wins. The maps do not change.
func MergeMaps(base, override map[string]int) []Pair {
	// A map value refers to the map, so copy base before the change.
	merged := maps.Clone(base)
	if merged == nil {
		// Clone of a nil map is nil, and Copy into a nil map panics.
		merged = make(map[string]int, len(override))
	}
	// Copy replaces the values of keys that are there.
	maps.Copy(merged, override)
	out := make([]Pair, 0, len(merged))
	for _, k := range slices.Sorted(maps.Keys(merged)) {
		out = append(out, Pair{k, merged[k]})
	}
	return out
}
merge_maps_test.go 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

package mergemaps

import (
	"maps"
	"slices"
	"testing"
)

var cases = []struct {
	name     string
	base     map[string]int
	override map[string]int
	want     []Pair
}{
	{"prices", map[string]int{"apple": 3, "pear": 5}, map[string]int{"pear": 6, "fig": 2}, []Pair{{"apple", 3}, {"fig", 2}, {"pear", 6}}},
	{"disjoint", map[string]int{"a": 1}, map[string]int{"b": 2}, []Pair{{"a", 1}, {"b", 2}}},
	{"empty-base", map[string]int{}, map[string]int{"a": 1}, []Pair{{"a", 1}}},
	{"empty-override", map[string]int{"a": 1}, map[string]int{}, []Pair{{"a", 1}}},
	{"both-empty", map[string]int{}, map[string]int{}, []Pair{}},
	{"same-keys", map[string]int{"a": 1, "b": 2}, map[string]int{"a": 9, "b": 8}, []Pair{{"a", 9}, {"b", 8}}},
	{"zero-wins", map[string]int{"a": 5}, map[string]int{"a": 0}, []Pair{{"a", 0}}},
	{"case", map[string]int{"a": 1}, map[string]int{"A": 2}, []Pair{{"A", 2}, {"a", 1}}},
}

func TestMergeMaps(t *testing.T) {
	for _, c := range cases {
		base, override := maps.Clone(c.base), maps.Clone(c.override)
		if got := MergeMaps(c.base, c.override); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
		if !maps.Equal(base, c.base) || !maps.Equal(override, c.override) {
			t.Errorf("%s: an input changed", c.name)
		}
	}
}

func TestNilBase(t *testing.T) {
	if got := MergeMaps(nil, map[string]int{"a": 1}); !slices.Equal(got, []Pair{{"a", 1}}) {
		t.Errorf("nil base: got %v", got)
	}
}
merge_maps.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

use std::collections::HashMap;

/// Returns the entries of both maps in key order; the value of `over` wins.
pub fn merge_maps<'a>(base: &HashMap<&'a str, i32>, over: &HashMap<&'a str, i32>) -> Vec<(&'a str, i32)> {
    // The clone keeps base as it is. extend replaces the values of keys that are there.
    let mut merged = base.clone();
    merged.extend(over.iter().map(|(&k, &v)| (k, v)));
    let mut out: Vec<(&'a str, i32)> = merged.into_iter().collect();
    out.sort();
    out
}
tests/merge_maps_test.rs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/merge-two-maps/.

use std::collections::HashMap;

use algo_merge_two_maps::merge_maps;

#[test]
fn cases() {
    type Pairs = Vec<(&'static str, i32)>;
    let cases: Vec<(&str, Pairs, Pairs, Pairs)> = vec![
        ("prices", vec![("apple", 3), ("pear", 5)], vec![("pear", 6), ("fig", 2)], vec![("apple", 3), ("fig", 2), ("pear", 6)]),
        ("disjoint", vec![("a", 1)], vec![("b", 2)], vec![("a", 1), ("b", 2)]),
        ("empty-base", vec![], vec![("a", 1)], vec![("a", 1)]),
        ("empty-override", vec![("a", 1)], vec![], vec![("a", 1)]),
        ("both-empty", vec![], vec![], vec![]),
        ("same-keys", vec![("a", 1), ("b", 2)], vec![("a", 9), ("b", 8)], vec![("a", 9), ("b", 8)]),
        ("zero-wins", vec![("a", 5)], vec![("a", 0)], vec![("a", 0)]),
        ("case", vec![("a", 1)], vec![("A", 2)], vec![("A", 2), ("a", 1)]),
    ];
    for (name, b, o, want) in cases {
        let base: HashMap<&str, i32> = b.into_iter().collect();
        let over: HashMap<&str, i32> = o.into_iter().collect();
        let (base_before, over_before) = (base.clone(), over.clone());
        assert_eq!(merge_maps(&base, &over), want, "{name}");
        assert_eq!(base, base_before, "{name}");
        assert_eq!(over, over_before, "{name}");
    }
}
merge_maps.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/merge-two-maps/.

# merge_maps KEY=VALUE... [-- KEY=VALUE...]
# The pairs before -- are the base map, and the pairs after it are the
# override map. Prints one line "KEY VALUE" for each key of either map, in
# ascending order of the key by its bytes. For a key in both maps, the value
# of the override map wins.
merge_maps() {
  local -A merged=()
  local arg
  for arg in "$@"; do
    if [[ $arg == -- ]]; then
      continue
    fi
    # The pairs after -- come later, so their values replace the base values.
    merged[${arg%%=*}]=${arg#*=}
  done
  for arg in "${!merged[@]}"; do
    printf '%s %s\n' "$arg" "${merged[$arg]}"
  done | LC_ALL=C sort
}
test_merge_maps.bats 28 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/merge-two-maps/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/merge_maps.sh"
}

check() { # check WANT ARG...
  local want got
  # %b turns each \n in WANT into a newline. The x keeps the trailing
  # newlines, which $(...) removes.
  want=$(printf '%b' "$1"; printf x)
  shift
  got=$(merge_maps "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "prices" { check "apple 3\nfig 2\npear 6\n" apple=3 pear=5 -- pear=6 fig=2; }
@test "disjoint" { check "a 1\nb 2\n" a=1 -- b=2; }
@test "empty-base" { check "a 1\n" -- a=1; }
@test "empty-override" { check "a 1\n" a=1; }
@test "both-empty" { check ""; }
@test "same-keys" { check "a 9\nb 8\n" a=1 b=2 -- a=9 b=8; }
@test "zero-wins" { check "a 0\n" a=5 -- a=0; }
@test "case" { check "A 2\na 1\n" a=1 -- A=2; }

References

  1. The Python Standard Library, Built-in Types, Mapping Types, dict; d | other; update
  2. MDN Web Docs, Spread syntax (...), Spread in object literals; Copying an array
  3. Go standard library, package maps, func Copy
  4. Rust standard library, struct HashMap, impl Extend<(K, V)>
  5. Java SE 25 API, Class Collectors, toMap(Function, Function)
  6. .NET API reference, Enumerable.ToDictionary method, Exceptions
  7. The Go Blog, Go maps in action, Declaration and initialization
  8. Rust standard library, enum Entry, or_insert
  9. cppreference.com, std::map::merge, Description
  10. cppreference.com, strcmp (C), Description
  11. Bash Reference Manual, 6.7 Arrays

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source