Programming Search⌘K

Taskintro

Use a map with a default value

Also called get with a default, getOrDefault, dict get default, map lookup with fallback, defaultdict.

Read keys from a map and use a fallback value for a key that is not in the map, without adding the key and without mixing up a missing key with a stored 0.

Task

Read keys from a map, and use a fallback value for a key that is not in the map. The function lookup(table, keys, fallback) returns one value for each key, in the order of keys. The value is the value of the key in table if table has the key, else fallback. The function does not change table. For example, lookup({"apple": 3, "pear": 5}, ["apple", "fig", "pear"], 0) is [3, 0, 5].

Each key has 1 or more ASCII letters. Each value and the fallback fit in a signed 32-bit integer. The map and the list of keys can be empty, and the list can have a key more than one time.

Solutions

Language Read with a default Count with a default
Python table.get(key, fallback) counts[w] = counts.get(w, 0) + 1
JavaScript, TypeScript table.get(key) ?? fallback counts.set(w, (counts.get(w) ?? 0) + 1)
Java table.getOrDefault(key, fallback) counts.merge(w, 1, Integer::sum)
C# table.GetValueOrDefault(key, fallback) counts[w] = counts.GetValueOrDefault(w) + 1
Go v, ok := table[key], then the fallback if !ok counts[w]++
Rust table.get(key).copied().unwrap_or(fallback) *counts.entry(w).or_insert(0) += 1
C bsearch, then the fallback for a null pointer (no map type)
C++ find, then the fallback for end() counts[w]++
Bash ${table[$key]-$fallback} counts[$w]=$(( ${counts[$w]-0} + 1 ))
  • Read with a default. Each solution uses an operation that tells a missing key from a key that is there, and that does not add the key. Python get does this: "Return the value for key if key is in the dictionary, else default."1 Java getOrDefault "Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key."2 In Go, the special form v, ok := a[x] gives a second value, and "The value of ok is true if the key x is present in the map, and false otherwise."3 C# GetValueOrDefault "Tries to get the value associated with the specified key in the dictionary"4, and gives the fallback if that fails.
  • Count with a default. To count, read the count with the default 0, add 1, and write the count back. Go and C++ do not need the default: a missing key in Go gives "the zero value for the element type"3, and C++ operator[] adds a missing key with the value 0. Python also has collections.Counter and defaultdict(int). See Count the items of each kind and Count word frequencies.
  • Group with a default. To group, the default is an empty list. Get the list of a key, or add an empty list for a missing key, then append to it. Rust or_insert_with "Ensures a value is in the entry by inserting the result of the default function if empty"5, and Python defaultdict(list) does the same. See Group items by a key.
  • A default that is added or not. A read with a default does not change the map. The entry API in Rust, computeIfAbsent in Java, defaultdict in Python and operator[] in C++ add the key with the default. Use these to count and group, but not to read only.
  • C. C has no map type. Here a map is an array of entries in key order, and bsearch finds a key. It returns a "Pointer to an element in the array that compares equal to *key, or null pointer if such element has not been found."6

Edge cases

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

  • empty-table: each key gets the fallback.
  • empty-keys: the result is empty.
  • zero-value: the key a has the value 0 and the fallback is 5. The result for a is 0. A test of the value for truth, such as table.get(key) or fallback in Python, gives 5.
  • repeat: a missing key two times gets the fallback two times. A solution that adds the key with the fallback changes the map, and the test finds that change.
  • case: A is not the key a, so it gets the fallback.

Pitfalls

  • Python or replaces a stored 0, and defaultdict adds the key on a read. get(key) or fallback gives the fallback for each false value, and 0 is false. For a defaultdict, a read of a missing key calls the factory, then "this value is inserted in the dictionary for the key, and returned."7 Thus a read only of a defaultdict makes it grow:
from collections import defaultdict

stock = {"apple": 3, "pear": 0}
print(stock.get("pear") or 5, stock.get("pear", 5))
counts = defaultdict(int)
print(counts["fig"], len(counts))
Output
5 0
0 1
  • JavaScript || replaces a stored 0. The ?? operator "returns its right-hand side operand when its left-hand side operand is null or undefined"8. But || "returns the right-hand side operand if the left operand is any falsy value, not only null or undefined."8 0 is falsy, so use ?? for a default:
const stock = new Map([["apple", 3], ["pear", 0]]);
console.log(stock.get("pear") || 5, stock.get("pear") ?? 5);
console.log(stock.get("fig") ?? 5);
Output
5 0
5
  • Java get gives null, and an int cannot hold null. get "Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key."2 An assignment of the Integer null to an int throws NullPointerException. Use getOrDefault:
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<String, Integer> stock = Map.of("apple", 3);
    try {
      int n = stock.get("fig");
      System.out.println(n);
    } catch (NullPointerException e) {
      System.out.println(e.getClass().getSimpleName());
    }
    System.out.println(stock.getOrDefault("fig", 0));
  }
}
Output
NullPointerException
0
  • C# counts[w]++ throws for a new word. The indexer reads the old count first, and "a KeyNotFoundException is thrown when a requested key is not present"4. Read the count with GetValueOrDefault:
using System;
using System.Collections.Generic;

var counts = new Dictionary<string, int>();
try
{
    counts["fig"]++;
}
catch (KeyNotFoundException e)
{
    Console.WriteLine(e.GetType().Name);
}
foreach (var word in new[] { "fig", "pear", "fig" })
{
    counts[word] = counts.GetValueOrDefault(word) + 1;
}
Console.WriteLine("fig=" + counts["fig"] + " pear=" + counts["pear"]);
Output
KeyNotFoundException
fig=2 pear=1
  • Go a missing key and a stored 0 look the same. If the map "does not contain such an entry, a[x] is the zero value for the element type of M"3. Thus a read of the stored 0 of pear and a read of the missing key fig both give 0. Use the second value to tell them apart:
package main

import "fmt"

func main() {
	stock := map[string]int{"apple": 3, "pear": 0}
	fmt.Println(stock["pear"], stock["fig"])
	_, inPear := stock["pear"]
	_, inFig := stock["fig"]
	fmt.Println(inPear, inFig)
}
Output
0 0
true false
  • Rust the argument of or_insert is made each time. or_insert "Ensures a value is in the entry by inserting the default if empty"5, but Rust makes the argument before the call, also when the key is there. For a default that costs something to make, use or_insert_with, which calls its function only for a missing key:
use std::collections::HashMap;

fn fallback() -> Vec<i32> {
    println!("made a default");
    Vec::new()
}

fn main() {
    let mut groups: HashMap<&str, Vec<i32>> = HashMap::new();
    groups.insert("odd", vec![1]);
    groups.entry("odd").or_insert(fallback()).push(3);
    groups.entry("odd").or_insert_with(fallback).push(5);
    println!("{:?}", groups["odd"]);
}
Output
made a default
[1, 3, 5]
  • C++ at throws for a missing key. For at, "If no such element exists, an exception of type std::out_of_range is thrown."9 operator[] does not throw, but it adds the key, and it does not compile for a const map. Use find and compare the result with end():
#include <iostream>
#include <stdexcept>
#include <string>
#include <unordered_map>

int main() {
    const std::unordered_map<std::string, int> stock{{"apple", 3}};
    try {
        std::cout << stock.at("fig") << '\n';
    } catch (const std::out_of_range &) {
        std::cout << "out_of_range\n";
    }
    auto it = stock.find("fig");
    std::cout << (it == stock.end() ? 0 : it->second) << '\n';
}
Output
out_of_range
0
  • C a function that returns the default loses the null pointer. A helper that returns 0 for a missing key gives 0 for a stored 0 too. Keep the pointer from bsearch, or give the fallback to the helper as an argument:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct entry {
    const char *key;
    int value;
};

static const struct entry stock[] = {{"apple", 3}, {"pear", 0}};

static int cmp(const void *key, const void *elem) {
    const struct entry *e = elem;
    return strcmp(key, e->key);
}

static int get_or_zero(const char *key) {
    const struct entry *e = bsearch(key, stock, 2, sizeof stock[0], cmp);
    return e == NULL ? 0 : e->value;
}

int main(void) {
    printf("%d %d\n", get_or_zero("pear"), get_or_zero("fig"));
    const struct entry *pear = bsearch("pear", stock, 2, sizeof stock[0], cmp);
    const struct entry *fig = bsearch("fig", stock, 2, sizeof stock[0], cmp);
    printf("%d %d\n", pear != NULL, fig != NULL);
    return 0;
}
Output
0 0
1 0
  • Bash :- also replaces an empty value. "Omitting the colon results in a test only for a parameter that is unset."10 Thus ${table[$key]:-fallback} gives the fallback for a key with an empty value, and ${table[$key]-fallback} gives the empty value:
declare -A note=([apple]=ripe [pear]=)
echo "[${note[pear]:-none}] [${note[pear]-none}] [${note[fig]-none}]"
Output
[none] [] [none]

Code

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

lookup.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.


def lookup(table: dict[str, int], keys: list[str], fallback: int) -> list[int]:
    """Return the value of each key in table, or fallback for a key not in table."""
    # get does not add the key, and it returns a stored 0 as 0.
    return [table.get(key, fallback) for key in keys]
test_lookup.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

import pytest

from lookup import lookup

CASES = {
    "prices": ({"apple": 3, "pear": 5}, ["apple", "fig", "pear"], 0, [3, 0, 5]),
    "negative-fallback": ({"a": 1}, ["b", "a"], -1, [-1, 1]),
    "empty-table": ({}, ["a", "b"], 7, [7, 7]),
    "empty-keys": ({"a": 1}, [], 0, []),
    "zero-value": ({"a": 0}, ["a", "b"], 5, [0, 5]),
    "repeat": ({"a": 1}, ["b", "b", "a"], 2, [2, 2, 1]),
    "case": ({"a": 1}, ["A"], 0, [0]),
}


@pytest.mark.parametrize("name", CASES)
def test_lookup(name):
    table, keys, fallback, want = CASES[name]
    before = dict(table)
    assert lookup(table, keys, fallback) == want
    assert table == before
lookup.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

#include "lookup.hpp"

std::vector<int> lookup(const std::unordered_map<std::string, int> &table, const std::vector<std::string> &keys, int fallback) {
    std::vector<int> out;
    out.reserve(keys.size());
    for (const auto &key : keys) {
        // find does not add the key. operator[] would add it with the value 0,
        // and at would throw std::out_of_range.
        auto it = table.find(key);
        out.push_back(it == table.end() ? fallback : it->second);
    }
    return out;
}
lookup.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

#pragma once

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

// lookup returns the value of each key in table, or fallback for a key that
// is not in table.
std::vector<int> lookup(const std::unordered_map<std::string, int> &table, const std::vector<std::string> &keys, int fallback);
test_lookup.cpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

#include "lookup.hpp"

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

static int failures = 0;

using Map = std::unordered_map<std::string, int>;
using Keys = std::vector<std::string>;
using Ints = std::vector<int>;

static void check(std::string_view name, const Map &table, const Keys &keys, int fallback, const Ints &want) {
    const Map before = table;
    if (lookup(table, keys, fallback) != want || table != before) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("prices", Map{{"apple", 3}, {"pear", 5}}, Keys{"apple", "fig", "pear"}, 0, Ints{3, 0, 5});
    check("negative-fallback", Map{{"a", 1}}, Keys{"b", "a"}, -1, Ints{-1, 1});
    check("empty-table", Map{}, Keys{"a", "b"}, 7, Ints{7, 7});
    check("empty-keys", Map{{"a", 1}}, Keys{}, 0, Ints{});
    check("zero-value", Map{{"a", 0}}, Keys{"a", "b"}, 5, Ints{0, 5});
    check("repeat", Map{{"a", 1}}, Keys{"b", "b", "a"}, 2, Ints{2, 2, 1});
    check("case", Map{{"a", 1}}, Keys{"A"}, 0, Ints{0});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Lookup.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

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

final class Lookup {
  private Lookup() {}

  /** Returns the value of each key in table, or fallback for a key not in table. */
  static List<Integer> lookup(Map<String, Integer> table, List<String> keys, int fallback) {
    // getOrDefault does not add the key. get would return null for a missing key.
    return keys.stream().map(key -> table.getOrDefault(key, fallback)).toList();
  }
}
LookupTest.java 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

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 LookupTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("prices", Map.of("apple", 3, "pear", 5), List.of("apple", "fig", "pear"), 0, List.of(3, 0, 5)),
        Arguments.of("negative-fallback", Map.of("a", 1), List.of("b", "a"), -1, List.of(-1, 1)),
        Arguments.of("empty-table", Map.of(), List.of("a", "b"), 7, List.of(7, 7)),
        Arguments.of("empty-keys", Map.of("a", 1), List.of(), 0, List.of()),
        Arguments.of("zero-value", Map.of("a", 0), List.of("a", "b"), 5, List.of(0, 5)),
        Arguments.of("repeat", Map.of("a", 1), List.of("b", "b", "a"), 2, List.of(2, 2, 1)),
        Arguments.of("case", Map.of("a", 1), List.of("A"), 0, List.of(0)));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void lookup(String name, Map<String, Integer> table, List<String> keys, int fallback, List<Integer> want) {
    // A HashMap copy can change, so the test also checks that the function does not change it.
    var t = new HashMap<>(table);
    assertEquals(want, Lookup.lookup(t, keys, fallback));
    assertEquals(table, t);
  }
}
lookup.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

#include "lookup.h"

#include <stdlib.h>
#include <string.h>

// cmp compares a key (a string) with the key of an entry.
static int cmp(const void *key, const void *elem) {
    const struct entry *e = elem;
    return strcmp(key, e->key);
}

void lookup(const struct entry *table, size_t n, const char *const *keys, size_t m, int fallback, int *out) {
    for (size_t i = 0; i < m; i++) {
        // bsearch returns a null pointer for a missing key, so a stored 0 and
        // a missing key are different.
        const struct entry *e = n == 0 ? NULL : bsearch(keys[i], table, n, sizeof table[0], cmp);
        out[i] = e == NULL ? fallback : e->value;
    }
}
lookup.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

#ifndef LOOKUP_H
#define LOOKUP_H

#include <stddef.h>

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

// lookup writes to out[i] the value of keys[i] in table (n entries), or
// fallback if table has no entry for keys[i]. out must have room for m ints.
void lookup(const struct entry *table, size_t n, const char *const *keys, size_t m, int fallback, int *out);

#endif
test_lookup.c 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

#include "lookup.h"

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

static int failures = 0;

#define L(...) {__VA_ARGS__}

// An empty array has a dummy item in it, because C has no empty array. The
// counts give the real lengths.
#define CHECK(name, n, t, m, k, fallback, ...)                                 \
    do {                                                                       \
        const struct entry table[] = t;                                        \
        struct entry before[sizeof table / sizeof table[0]];                   \
        const char *const keys[] = k;                                          \
        const int want[] = {__VA_ARGS__};                                      \
        int out[sizeof keys / sizeof keys[0]];                                 \
        memcpy(before, table, sizeof table);                                   \
        lookup(table, n, keys, m, fallback, out);                              \
        if (memcmp(out, want, (m) * sizeof(int)) != 0 ||                       \
            memcmp(before, table, sizeof table) != 0) {                        \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("prices", 2, L({"apple", 3}, {"pear", 5}), 3, L("apple", "fig", "pear"), 0, 3, 0, 5);
    CHECK("negative-fallback", 1, L({"a", 1}), 2, L("b", "a"), -1, -1, 1);
    CHECK("empty-table", 0, L({"", 0}), 2, L("a", "b"), 7, 7, 7);
    CHECK("empty-keys", 1, L({"a", 1}), 0, L(""), 0, 0);
    CHECK("zero-value", 1, L({"a", 0}), 2, L("a", "b"), 5, 0, 5);
    CHECK("repeat", 1, L({"a", 1}), 3, L("b", "b", "a"), 2, 2, 2, 1);
    CHECK("case", 1, L({"a", 1}), 1, L("A"), 0, 0);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Lookup.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

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

public static class Lookup
{
    // Get returns the value of each key in table, or fallback for a key not in table.
    public static int[] Get(IReadOnlyDictionary<string, int> table, string[] keys, int fallback)
    {
        // GetValueOrDefault does not add the key. The indexer would throw
        // KeyNotFoundException for a missing key.
        return keys.Select(key => table.GetValueOrDefault(key, fallback)).ToArray();
    }
}
LookupTests.cs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

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

public sealed class LookupTests
{
    public static TheoryData<string, string[], int[], string[], int, int[]> Cases => new()
    {
        { "prices", new string[] { "apple", "pear" }, new int[] { 3, 5 }, new string[] { "apple", "fig", "pear" }, 0, new int[] { 3, 0, 5 } },
        { "negative-fallback", new string[] { "a" }, new int[] { 1 }, new string[] { "b", "a" }, -1, new int[] { -1, 1 } },
        { "empty-table", new string[0], new int[0], new string[] { "a", "b" }, 7, new int[] { 7, 7 } },
        { "empty-keys", new string[] { "a" }, new int[] { 1 }, new string[0], 0, new int[0] },
        { "zero-value", new string[] { "a" }, new int[] { 0 }, new string[] { "a", "b" }, 5, new int[] { 0, 5 } },
        { "repeat", new string[] { "a" }, new int[] { 1 }, new string[] { "b", "b", "a" }, 2, new int[] { 2, 2, 1 } },
        { "case", new string[] { "a" }, new int[] { 1 }, new string[] { "A" }, 0, new int[] { 0 } },
    };

    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[] tableKeys, int[] tableValues, string[] keys, int fallback, int[] want)
    {
        Assert.NotNull(name);
        var table = Map(tableKeys, tableValues);
        Assert.Equal(want, Lookup.Get(table, keys, fallback));
        Assert.Equal(Map(tableKeys, tableValues), table);
    }
}
lookup.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

/**
 * @param {Map<string, number>} table
 * @param {string[]} keys
 * @param {number} fallback
 * @returns {number[]}
 */
export function lookup(table, keys, fallback) {
  // ?? uses the fallback only for undefined, so a stored 0 stays 0.
  // || would also replace 0.
  return keys.map((key) => table.get(key) ?? fallback);
}
lookup.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

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

import { lookup } from "./lookup.js";

const cases = [
  ["prices", new Map([["apple", 3], ["pear", 5]]), ["apple", "fig", "pear"], 0, [3, 0, 5]],
  ["negative-fallback", new Map([["a", 1]]), ["b", "a"], -1, [-1, 1]],
  ["empty-table", new Map(), ["a", "b"], 7, [7, 7]],
  ["empty-keys", new Map([["a", 1]]), [], 0, []],
  ["zero-value", new Map([["a", 0]]), ["a", "b"], 5, [0, 5]],
  ["repeat", new Map([["a", 1]]), ["b", "b", "a"], 2, [2, 2, 1]],
  ["case", new Map([["a", 1]]), ["A"], 0, [0]],
];

for (const [name, table, keys, fallback, want] of cases) {
  test(name, () => {
    const before = [...table];
    assert.deepEqual(lookup(table, keys, fallback), want);
    assert.deepEqual([...table], before);
  });
}
lookup.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

export function lookup(table: ReadonlyMap<string, number>, keys: readonly string[], fallback: number): number[] {
  // ?? uses the fallback only for undefined, so a stored 0 stays 0.
  // || would also replace 0.
  return keys.map((key) => table.get(key) ?? fallback);
}
lookup.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

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

import { lookup } from "./lookup.ts";

const cases: [string, Map<string, number>, string[], number, number[]][] = [
  ["prices", new Map([["apple", 3], ["pear", 5]]), ["apple", "fig", "pear"], 0, [3, 0, 5]],
  ["negative-fallback", new Map([["a", 1]]), ["b", "a"], -1, [-1, 1]],
  ["empty-table", new Map<string, number>(), ["a", "b"], 7, [7, 7]],
  ["empty-keys", new Map([["a", 1]]), [], 0, []],
  ["zero-value", new Map([["a", 0]]), ["a", "b"], 5, [0, 5]],
  ["repeat", new Map([["a", 1]]), ["b", "b", "a"], 2, [2, 2, 1]],
  ["case", new Map([["a", 1]]), ["A"], 0, [0]],
];

for (const [name, table, keys, fallback, want] of cases) {
  test(name, () => {
    const before = [...table];
    assert.deepEqual(lookup(table, keys, fallback), want);
    assert.deepEqual([...table], before);
  });
}
lookup.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

// Package lookup reads keys from a map with a default value.
package lookup

// Lookup returns the value of each key in table, or fallback for a key that
// is not in table. The map does not change.
func Lookup(table map[string]int, keys []string, fallback int) []int {
	out := make([]int, 0, len(keys))
	for _, key := range keys {
		// table[key] alone gives 0 for a missing key. The second result
		// tells a missing key from a stored 0.
		v, ok := table[key]
		if !ok {
			v = fallback
		}
		out = append(out, v)
	}
	return out
}
lookup_test.go 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

package lookup

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

var cases = []struct {
	name     string
	table    map[string]int
	keys     []string
	fallback int
	want     []int
}{
	{"prices", map[string]int{"apple": 3, "pear": 5}, []string{"apple", "fig", "pear"}, 0, []int{3, 0, 5}},
	{"negative-fallback", map[string]int{"a": 1}, []string{"b", "a"}, -1, []int{-1, 1}},
	{"empty-table", map[string]int{}, []string{"a", "b"}, 7, []int{7, 7}},
	{"empty-keys", map[string]int{"a": 1}, []string{}, 0, []int{}},
	{"zero-value", map[string]int{"a": 0}, []string{"a", "b"}, 5, []int{0, 5}},
	{"repeat", map[string]int{"a": 1}, []string{"b", "b", "a"}, 2, []int{2, 2, 1}},
	{"case", map[string]int{"a": 1}, []string{"A"}, 0, []int{0}},
}

func TestLookup(t *testing.T) {
	for _, c := range cases {
		before := maps.Clone(c.table)
		if got := Lookup(c.table, c.keys, c.fallback); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
		if !maps.Equal(before, c.table) {
			t.Errorf("%s: the table changed", c.name)
		}
	}
}

func TestNilTable(t *testing.T) {
	// A read from a nil map is fine and gives no entry.
	if got := Lookup(nil, []string{"a"}, 4); !slices.Equal(got, []int{4}) {
		t.Errorf("nil table: got %v", got)
	}
}
lookup.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

use std::collections::HashMap;

/// Returns the value of each key in `table`, or `fallback` for a key not in `table`.
pub fn lookup(table: &HashMap<&str, i32>, keys: &[&str], fallback: i32) -> Vec<i32> {
    // get gives an Option, so a missing key and a stored 0 are different.
    keys.iter().map(|key| table.get(key).copied().unwrap_or(fallback)).collect()
}
tests/lookup_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

use std::collections::HashMap;

use algo_use_a_map_with_a_default_value::lookup;

#[test]
fn cases() {
    type Pairs = Vec<(&'static str, i32)>;
    let cases: Vec<(&str, Pairs, Vec<&str>, i32, Vec<i32>)> = vec![
        ("prices", vec![("apple", 3), ("pear", 5)], vec!["apple", "fig", "pear"], 0, vec![3, 0, 5]),
        ("negative-fallback", vec![("a", 1)], vec!["b", "a"], -1, vec![-1, 1]),
        ("empty-table", vec![], vec!["a", "b"], 7, vec![7, 7]),
        ("empty-keys", vec![("a", 1)], vec![], 0, vec![]),
        ("zero-value", vec![("a", 0)], vec!["a", "b"], 5, vec![0, 5]),
        ("repeat", vec![("a", 1)], vec!["b", "b", "a"], 2, vec![2, 2, 1]),
        ("case", vec![("a", 1)], vec!["A"], 0, vec![0]),
    ];
    for (name, t, keys, fallback, want) in cases {
        let table: HashMap<&str, i32> = t.into_iter().collect();
        let before = table.clone();
        assert_eq!(lookup(&table, &keys, fallback), want, "{name}");
        assert_eq!(table, before, "{name}");
    }
}
lookup.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

# lookup FALLBACK KEY=VALUE... [-- KEY...]
# The pairs before -- are the map, and the words after it are the keys to
# read. Prints one line for each key: the value of the key in the map, or
# FALLBACK if the map has no such key.
lookup() {
  local fallback=$1
  shift
  local -A table=()
  while (($# > 0)) && [[ $1 != -- ]]; do
    table[${1%%=*}]=${1#*=}
    shift
  done
  if (($# > 0)); then
    shift
  fi
  local key
  for key in "$@"; do
    # ${name-word} uses word only if name is unset. ${name:-word} would also
    # use it for an empty value.
    printf '%s\n' "${table[$key]-$fallback}"
  done
}
test_lookup.bats 27 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-map-with-a-default-value/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/lookup.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=$(lookup "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "prices" { check "3\n0\n5\n" 0 apple=3 pear=5 -- apple fig pear; }
@test "negative-fallback" { check "-1\n1\n" -1 a=1 -- b a; }
@test "empty-table" { check "7\n7\n" 7 -- a b; }
@test "empty-keys" { check "" 0 a=1; }
@test "zero-value" { check "0\n5\n" 5 a=0 -- a b; }
@test "repeat" { check "2\n2\n1\n" 2 a=1 -- b b a; }
@test "case" { check "0\n" 0 a=1 -- A; }

References

  1. The Python Standard Library, Built-in Types, Mapping Types, dict; get
  2. Java SE 25 API, Interface Map, get; getOrDefault
  3. The Go Programming Language Specification, Index expressions
  4. .NET API reference, Dictionary<TKey,TValue> class, Examples; Extension Methods, GetValueOrDefault
  5. Rust standard library, enum Entry, or_insert; or_insert_with
  6. cppreference.com, bsearch, bsearch_s (C), Return value
  7. The Python Standard Library, collections, defaultdict objects; __missing__
  8. MDN Web Docs, Nullish coalescing operator (??), Description
  9. cppreference.com, std::unordered_map::at, Description
  10. Bash Reference Manual, 3.5.3 Shell Parameter Expansion

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