Taskintro
Iterate over a map
Also called loop over a dictionary, iterate over map entries, walk the keys and values of a map, for each entry in a map.
Walk the entries of a map in key order to print one line for each entry, then walk the values to add them up.
- Evidence
- Code in 10 languages
Task
Walk the entries of a map. The function score_lines(scores) takes a map from names to scores. It returns one line key=value for each entry, in ascending order of the key by its bytes, then one line total=N, where N is the sum of the values. For example, score_lines({"bob": 7, "amy": 9, "cal": 4}) is ["amy=9", "bob=7", "cal=4", "total=20"].
Each key has 1 or more ASCII letters. Each value is from -1000000 to 1000000, and the map has at most 1000 entries, so the total fits in a signed 32-bit integer. The map can be empty. Then the result is ["total=0"].
Solutions
| Language | Entries in key order | Values |
|---|---|---|
| Python | sorted(scores.items()) |
sum(scores.values()) |
| JavaScript, TypeScript | [...scores.keys()].sort(), then scores.get(key) |
for (const value of scores.values()) |
| Java | new TreeMap<>(scores).entrySet() |
for (int value : scores.values()) |
| C# | scores.OrderBy(p => p.Key, StringComparer.Ordinal) |
foreach (var value in scores.Values) |
| Go | slices.Sorted(maps.Keys(scores)), then scores[k] |
for _, v := range scores |
| Rust | scores.iter().collect(), then sort() |
scores.values().sum() |
| C | qsort of an array of pointers to the entries |
a loop over the sorted pointers |
| C++ | a std::map copy of the std::unordered_map |
for (const auto &[key, value] : scores) |
| Bash | "${!map[@]}", then LC_ALL=C sort |
"${map[@]}" |
- Three ways to walk. A map gives its keys, its values and its pairs. In Python,
items(),keys()andvalues()give views, and "Keys and values are iterated over in insertion order."1 A JavaScriptMap"iterates entries, keys, and values in the order of entry insertion."2 Use the pairs when the loop needs the key and the value, so it does not look up each key again. - The order. Insertion order is not key order, and a hash map gives no order at all. In Go, "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next."3 A Rust
HashMapgives "An iterator visiting all key-value pairs in arbitrary order."4 For a .NETDictionary, "The order in which the items are returned is undefined."5 Thus each solution sorts the keys, or copies the entries to a sorted map, before it makes the lines. - The total. The sum does not depend on the order, so each solution walks the values in the order of the map.
- C. The input is an array of entries with different keys. The function sorts an array of pointers to the entries, so the input does not change, then writes the lines to a buffer with
snprintf. It returns -1 if the text does not fit. - Bash. The function takes the entries as
KEY=VALUEarguments and prints the lines."${!map[@]}"gives the keys, and"${map[@]}"gives the values.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: an empty map gives onlytotal=0.case: the keysA,B,aandbare in byte order, so the upper case keys come first.negative: the values -5 and 5 givea=-5,b=5andtotal=0.prefix: the keyacomes beforeab, andabcomes beforeabc.reverse: ten keys inserted fromjdown toacome out fromatoj.
Pitfalls
- Python a change of size during a loop raises RuntimeError. "Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries."1 In the example, the first loop deletes
boband then fails. Loop overlist(scores), a copy of the keys:
scores = {"amy": 9, "bob": 3, "cal": 4}
try:
for name in scores:
if scores[name] < 5:
del scores[name]
except RuntimeError as e:
print(type(e).__name__)
print(scores)
for name in list(scores):
if scores[name] < 5:
del scores[name]
print(scores)
RuntimeError
{'amy': 9, 'cal': 4}
{'amy': 9}
- JavaScript an object puts integer keys first. For an object, "all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation."6 A
Mapkeeps the insertion order of all keys. Neither order is key order, so sort the keys:
const object = { b: 1, 10: 2, a: 3, 2: 4 };
console.log(Object.keys(object));
const map = new Map([["b", 1], ["10", 2], ["a", 3], ["2", 4]]);
console.log([...map.keys()]);
console.log([...map.keys()].sort());
[ '2', '10', 'b', 'a' ]
[ 'b', '10', 'a', '2' ]
[ '10', '2', 'a', 'b' ]
- Java a change during a for-each loop throws ConcurrentModificationException. For
keySet(), "If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined."7 AHashMapiterator is fail-fast: "if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."8 UseremoveIfon a view, or the remove method of the iterator:
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>(Map.of("a", 1, "b", 7, "c", 3));
try {
for (String key : scores.keySet()) {
if (scores.get(key) < 5) {
scores.remove(key);
}
}
} catch (ConcurrentModificationException e) {
System.out.println(e.getClass().getSimpleName());
}
scores.values().removeIf(v -> v < 5);
System.out.println(new TreeMap<>(scores));
}
}
ConcurrentModificationException
{b=7}
- C# an Add during foreach throws InvalidOperationException. "The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it."5 In the example, the first
Addworks, and the next step of the loop throws. Loop over a copy of the keys, made withToList:
using System;
using System.Collections.Generic;
using System.Linq;
var scores = new Dictionary<string, int> { ["amy"] = 9, ["bob"] = 3 };
try
{
foreach (var key in scores.Keys)
{
scores.Add("cal", 4);
}
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.GetType().Name);
}
foreach (var key in scores.Keys.ToList())
{
if (scores[key] < 5)
{
scores.Remove(key);
}
}
Console.WriteLine(string.Join(" ", scores.Keys.Order(StringComparer.Ordinal)));
InvalidOperationException
amy
- Go a new entry during a range loop can be skipped or not. A delete in the loop is safe: "If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced."3 But "If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped."3 Thus do not add entries in the loop. The example deletes in the loop, then sorts the keys for a fixed order:
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
scores := map[string]int{"amy": 9, "bob": 3, "cal": 4, "dan": 8}
for k, v := range scores {
if v < 5 {
delete(scores, k)
}
}
fmt.Println(slices.Sorted(maps.Keys(scores)))
}
[amy dan]
- Rust a loop over a HashMap cannot change it. The loop borrows the map, so the body cannot call
removeon it.retaindeletes entries as it walks them: it will "remove all pairs (k, v) for which f(&k, &mut v) returns false."4 The order is still arbitrary, so sort the keys:
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::from([("amy", 9), ("bob", 3), ("cal", 4), ("dan", 8)]);
scores.retain(|_, v| *v >= 5);
let mut keys: Vec<&str> = scores.keys().copied().collect();
keys.sort();
println!("{keys:?}");
}
["amy", "dan"]
- C++ erase makes the iterator invalid. "References and iterators to the erased elements are invalidated."9 A
++itaftererase(it)uses an invalid iterator. Use the iterator thaterasereturns, orstd::erase_if:
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> scores{{"amy", 9}, {"bob", 3}, {"cal", 4}, {"dan", 8}};
for (auto it = scores.begin(); it != scores.end();) {
if (it->second < 5) {
it = scores.erase(it);
} else {
++it;
}
}
std::cout << scores.size() << ' ' << scores.contains("amy") << scores.contains("bob") << '\n';
std::erase_if(scores, [](const auto &p) { return p.first == "dan"; });
std::cout << scores.size() << '\n';
}
2 10
1
- C twalk calls postorder the visit between the children. POSIX
twalkvisits each node of atsearchtree up to three times. It uses "preorder, postorder, and endorder to refer respectively to visiting a node before any of its children, after its left child and before its right, and after both its children."10 Other texts call the middle visit inorder, "which could result in some confusion over the meaning of postorder."10 For the keys in order, print a node onpostorderand onleaf:
#define _XOPEN_SOURCE 700
#include <search.h>
#include <stdio.h>
#include <string.h>
static int cmp(const void *a, const void *b) {
return strcmp(a, b);
}
static void first_visit(const void *node, VISIT which, int depth) {
(void)depth;
if (which == preorder || which == leaf) {
printf("%s", *(char *const *)node);
}
}
static void in_order(const void *node, VISIT which, int depth) {
(void)depth;
if (which == postorder || which == leaf) {
printf("%s", *(char *const *)node);
}
}
int main(void) {
void *root = NULL;
char *keys[] = {"b", "a", "c"};
for (int i = 0; i < 3; i++) {
tsearch(keys[i], &root, cmp);
}
twalk(root, first_visit);
printf("\n");
twalk(root, in_order);
printf("\n");
return 0;
}
bac
abc
- Bash an unquoted list of keys splits a key with a space.
${!map[@]}and${!map[*]}"expand to the indices assigned in array variable name."11 Only in double quotes does${name[@]}give one word for each item: it "expands each element of name to a separate word."11 In the example, the keynew yorkgives two words without the quotes:
f() {
local -A map=(["new york"]=8 [oslo]=2)
local key n=0
for key in ${!map[@]}; do
n=$((n + 1))
done
echo "$n"
n=0
for key in "${!map[@]}"; do
n=$((n + 1))
done
echo "$n"
}
f
3
2
Related tasks
- Create a map: create the map that this task walks.
- Merge two maps: combine the entries of two maps.
- Sort with a custom key: sort the entries by the value, not the key.
- Group items by a key: build a map from a list, then walk it in key order.
- Iterate over the characters of a string: the same task for the characters of a string.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-over-a-map/.
def score_lines(scores: dict[str, int]) -> list[str]:
"""Return a line key=value for each entry in key order, then the total of the values."""
# A dict gives its keys in insertion order, so sort the items.
lines = [f"{key}={value}" for key, value in sorted(scores.items())]
lines.append(f"total={sum(scores.values())}")
return lines
test_score_lines.py 22 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-over-a-map/.
import pytest
from score_lines import score_lines
CASES = {
"scores": ({"bob": 7, "amy": 9, "cal": 4}, ["amy=9", "bob=7", "cal=4", "total=20"]),
"one": ({"x": 1}, ["x=1", "total=1"]),
"empty": ({}, ["total=0"]),
"case": ({"b": 1, "B": 2, "a": 3, "A": 4}, ["A=4", "B=2", "a=3", "b=1", "total=10"]),
"negative": ({"a": -5, "b": 5}, ["a=-5", "b=5", "total=0"]),
"prefix": ({"abc": 3, "a": 2, "ab": 1}, ["a=2", "ab=1", "abc=3", "total=6"]),
"reverse": ({"j": 1, "i": 2, "h": 3, "g": 4, "f": 5, "e": 6, "d": 7, "c": 8, "b": 9, "a": 10}, ["a=10", "b=9", "c=8", "d=7", "e=6", "f=5", "g=4", "h=3", "i=2", "j=1", "total=55"]),
}
@pytest.mark.parametrize("name", CASES)
def test_score_lines(name):
scores, want = CASES[name]
assert score_lines(scores) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
#include "score_lines.hpp"
#include <map>
std::vector<std::string> score_lines(const std::unordered_map<std::string, int> &scores) {
std::vector<std::string> lines;
// An unordered_map gives no order. A std::map gives its entries in key order.
const std::map<std::string, int> sorted(scores.begin(), scores.end());
for (const auto &[key, value] : sorted) {
lines.push_back(key + "=" + std::to_string(value));
}
int total = 0;
for (const auto &[key, value] : scores) {
total += value;
}
lines.push_back("total=" + std::to_string(total));
return lines;
}
score_lines.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
#pragma once
#include <string>
#include <unordered_map>
#include <vector>
// score_lines returns a line key=value for each entry in ascending order of
// the key, then the line total=N with the sum of the values.
std::vector<std::string> score_lines(const std::unordered_map<std::string, int> &scores);
test_score_lines.cpp 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
#include "score_lines.hpp"
#include <iostream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::unordered_map<std::string, int> &scores, const std::vector<std::string> &want) {
if (score_lines(scores) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("scores", {{"bob", 7}, {"amy", 9}, {"cal", 4}}, {"amy=9", "bob=7", "cal=4", "total=20"});
check("one", {{"x", 1}}, {"x=1", "total=1"});
check("empty", {}, {"total=0"});
check("case", {{"b", 1}, {"B", 2}, {"a", 3}, {"A", 4}}, {"A=4", "B=2", "a=3", "b=1", "total=10"});
check("negative", {{"a", -5}, {"b", 5}}, {"a=-5", "b=5", "total=0"});
check("prefix", {{"abc", 3}, {"a", 2}, {"ab", 1}}, {"a=2", "ab=1", "abc=3", "total=6"});
check("reverse", {{"j", 1}, {"i", 2}, {"h", 3}, {"g", 4}, {"f", 5}, {"e", 6}, {"d", 7}, {"c", 8}, {"b", 9}, {"a", 10}}, {"a=10", "b=9", "c=8", "d=7", "e=6", "f=5", "g=4", "h=3", "i=2", "j=1", "total=55"});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
final class ScoreLines {
private ScoreLines() {}
/** Returns a line key=value for each entry in key order, then the total of the values. */
static List<String> scoreLines(Map<String, Integer> scores) {
List<String> lines = new ArrayList<>();
// A HashMap gives no order. A TreeMap gives its entries in key order.
for (Map.Entry<String, Integer> e : new TreeMap<>(scores).entrySet()) {
lines.add(e.getKey() + "=" + e.getValue());
}
int total = 0;
for (int value : scores.values()) {
total += value;
}
lines.add("total=" + total);
return lines;
}
}
ScoreLinesTest.java 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
import static org.junit.jupiter.api.Assertions.assertEquals;
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 ScoreLinesTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("scores", Map.of("bob", 7, "amy", 9, "cal", 4), List.of("amy=9", "bob=7", "cal=4", "total=20")),
Arguments.of("one", Map.of("x", 1), List.of("x=1", "total=1")),
Arguments.of("empty", Map.of(), List.of("total=0")),
Arguments.of("case", Map.of("b", 1, "B", 2, "a", 3, "A", 4), List.of("A=4", "B=2", "a=3", "b=1", "total=10")),
Arguments.of("negative", Map.of("a", -5, "b", 5), List.of("a=-5", "b=5", "total=0")),
Arguments.of("prefix", Map.of("abc", 3, "a", 2, "ab", 1), List.of("a=2", "ab=1", "abc=3", "total=6")),
Arguments.of("reverse", Map.of("j", 1, "i", 2, "h", 3, "g", 4, "f", 5, "e", 6, "d", 7, "c", 8, "b", 9, "a", 10), List.of("a=10", "b=9", "c=8", "d=7", "e=6", "f=5", "g=4", "h=3", "i=2", "j=1", "total=55")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void scoreLines(String name, Map<String, Integer> scores, List<String> want) {
assertEquals(want, ScoreLines.scoreLines(scores));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
#include "score_lines.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// by_key compares two items of the array of pointers. qsort gives the
// comparison a pointer to each item, so each argument points to a pointer.
static int by_key(const void *a, const void *b) {
const struct entry *x = *(const struct entry *const *)a;
const struct entry *y = *(const struct entry *const *)b;
return strcmp(x->key, y->key);
}
int score_lines(const struct entry *map, size_t n, const struct entry **sorted, char *buf, size_t cap) {
for (size_t i = 0; i < n; i++) {
sorted[i] = &map[i];
}
if (n > 0) {
qsort(sorted, n, sizeof sorted[0], by_key);
}
size_t len = 0;
int total = 0;
for (size_t i = 0; i <= n; i++) {
int w;
if (i < n) {
w = snprintf(buf + len, cap - len, "%s=%d\n", sorted[i]->key, sorted[i]->value);
total += sorted[i]->value;
} else {
w = snprintf(buf + len, cap - len, "total=%d\n", total);
}
if (w < 0 || (size_t)w >= cap - len) {
return -1;
}
len += (size_t)w;
}
return (int)len;
}
score_lines.h 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
#ifndef SCORE_LINES_H
#define SCORE_LINES_H
#include <stddef.h>
// An entry of the map. The keys of a map are all different.
struct entry {
const char *key;
int value;
};
// score_lines writes one line "key=value\n" for each of the n entries, in
// ascending order of the key, then the line "total=N\n" with the sum of the
// values, to buf. sorted must have room for n pointers. It returns the length
// of the text, or -1 if the text and its terminating null do not fit in cap.
int score_lines(const struct entry *map, size_t n, const struct entry **sorted, char *buf, size_t cap);
#endif
test_score_lines.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
#include "score_lines.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
// count gives the real length.
#define CHECK(name, n, given, want) \
do { \
const struct entry g[] = given; \
const struct entry *sorted[sizeof g / sizeof g[0]]; \
char buf[256]; \
int got = score_lines(g, n, sorted, buf, sizeof buf); \
if (got != (int)strlen(want) || strcmp(buf, want) != 0) { \
fprintf(stderr, "case %s failed\n", name); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("scores", 3, L({"bob", 7}, {"amy", 9}, {"cal", 4}), "amy=9\nbob=7\ncal=4\ntotal=20\n");
CHECK("one", 1, L({"x", 1}), "x=1\ntotal=1\n");
CHECK("empty", 0, L({"", 0}), "total=0\n");
CHECK("case", 4, L({"b", 1}, {"B", 2}, {"a", 3}, {"A", 4}), "A=4\nB=2\na=3\nb=1\ntotal=10\n");
CHECK("negative", 2, L({"a", -5}, {"b", 5}), "a=-5\nb=5\ntotal=0\n");
CHECK("prefix", 3, L({"abc", 3}, {"a", 2}, {"ab", 1}), "a=2\nab=1\nabc=3\ntotal=6\n");
CHECK("reverse", 10, L({"j", 1}, {"i", 2}, {"h", 3}, {"g", 4}, {"f", 5}, {"e", 6}, {"d", 7}, {"c", 8}, {"b", 9}, {"a", 10}), "a=10\nb=9\nc=8\nd=7\ne=6\nf=5\ng=4\nh=3\ni=2\nj=1\ntotal=55\n");
char small[8];
const struct entry one[] = {{"apple", 3}};
const struct entry *sorted[1];
if (score_lines(one, 1, sorted, small, sizeof small) != -1) {
fprintf(stderr, "case small failed\n");
failures++;
}
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
using System;
using System.Collections.Generic;
using System.Linq;
public static class ScoreLines
{
// Lines returns a line key=value for each entry in key order, then the total of the values.
public static List<string> Lines(Dictionary<string, int> scores)
{
var lines = new List<string>();
// The order of a Dictionary is undefined. StringComparer.Ordinal compares the chars.
foreach (var (key, value) in scores.OrderBy(p => p.Key, StringComparer.Ordinal))
{
lines.Add($"{key}={value}");
}
var total = 0;
foreach (var value in scores.Values)
{
total += value;
}
lines.Add($"total={total}");
return lines;
}
}
ScoreLinesTests.cs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
using System.Linq;
using Xunit;
public sealed class ScoreLinesTests
{
public static TheoryData<string, string[], int[], string[]> Cases => new()
{
{ "scores", new string[] { "bob", "amy", "cal" }, new int[] { 7, 9, 4 }, new string[] { "amy=9", "bob=7", "cal=4", "total=20" } },
{ "one", new string[] { "x" }, new int[] { 1 }, new string[] { "x=1", "total=1" } },
{ "empty", new string[0], new int[0], new string[] { "total=0" } },
{ "case", new string[] { "b", "B", "a", "A" }, new int[] { 1, 2, 3, 4 }, new string[] { "A=4", "B=2", "a=3", "b=1", "total=10" } },
{ "negative", new string[] { "a", "b" }, new int[] { -5, 5 }, new string[] { "a=-5", "b=5", "total=0" } },
{ "prefix", new string[] { "abc", "a", "ab" }, new int[] { 3, 2, 1 }, new string[] { "a=2", "ab=1", "abc=3", "total=6" } },
{ "reverse", new string[] { "j", "i", "h", "g", "f", "e", "d", "c", "b", "a" }, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, new string[] { "a=10", "b=9", "c=8", "d=7", "e=6", "f=5", "g=4", "h=3", "i=2", "j=1", "total=55" } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, string[] keys, int[] values, string[] want)
{
Assert.NotNull(name);
var scores = keys.Zip(values).ToDictionary(p => p.First, p => p.Second);
Assert.Equal(want, ScoreLines.Lines(scores));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
/**
* @param {Map<string, number>} scores
* @returns {string[]}
*/
export function scoreLines(scores) {
const lines = [];
// A Map gives its keys in insertion order. sort() without a function
// compares strings by their UTF-16 code units, which is byte order for ASCII.
for (const key of [...scores.keys()].sort()) {
lines.push(`${key}=${scores.get(key)}`);
}
let total = 0;
for (const value of scores.values()) {
total += value;
}
lines.push(`total=${total}`);
return lines;
}
score_lines.test.js 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { scoreLines } from "./score_lines.js";
const cases = [
["scores", new Map([["bob", 7], ["amy", 9], ["cal", 4]]), ["amy=9", "bob=7", "cal=4", "total=20"]],
["one", new Map([["x", 1]]), ["x=1", "total=1"]],
["empty", new Map(), ["total=0"]],
["case", new Map([["b", 1], ["B", 2], ["a", 3], ["A", 4]]), ["A=4", "B=2", "a=3", "b=1", "total=10"]],
["negative", new Map([["a", -5], ["b", 5]]), ["a=-5", "b=5", "total=0"]],
["prefix", new Map([["abc", 3], ["a", 2], ["ab", 1]]), ["a=2", "ab=1", "abc=3", "total=6"]],
["reverse", new Map([["j", 1], ["i", 2], ["h", 3], ["g", 4], ["f", 5], ["e", 6], ["d", 7], ["c", 8], ["b", 9], ["a", 10]]), ["a=10", "b=9", "c=8", "d=7", "e=6", "f=5", "g=4", "h=3", "i=2", "j=1", "total=55"]],
];
for (const [name, scores, want] of cases) {
test(name, () => {
assert.deepEqual(scoreLines(scores), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
export function scoreLines(scores: ReadonlyMap<string, number>): string[] {
const lines: string[] = [];
// A Map gives its keys in insertion order. sort() without a function
// compares strings by their UTF-16 code units, which is byte order for ASCII.
for (const key of [...scores.keys()].sort()) {
lines.push(`${key}=${scores.get(key)}`);
}
let total = 0;
for (const value of scores.values()) {
total += value;
}
lines.push(`total=${total}`);
return lines;
}
score_lines.test.ts 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { scoreLines } from "./score_lines.ts";
const cases: [string, Map<string, number>, string[]][] = [
["scores", new Map([["bob", 7], ["amy", 9], ["cal", 4]]), ["amy=9", "bob=7", "cal=4", "total=20"]],
["one", new Map([["x", 1]]), ["x=1", "total=1"]],
["empty", new Map<string, number>(), ["total=0"]],
["case", new Map([["b", 1], ["B", 2], ["a", 3], ["A", 4]]), ["A=4", "B=2", "a=3", "b=1", "total=10"]],
["negative", new Map([["a", -5], ["b", 5]]), ["a=-5", "b=5", "total=0"]],
["prefix", new Map([["abc", 3], ["a", 2], ["ab", 1]]), ["a=2", "ab=1", "abc=3", "total=6"]],
["reverse", new Map([["j", 1], ["i", 2], ["h", 3], ["g", 4], ["f", 5], ["e", 6], ["d", 7], ["c", 8], ["b", 9], ["a", 10]]), ["a=10", "b=9", "c=8", "d=7", "e=6", "f=5", "g=4", "h=3", "i=2", "j=1", "total=55"]],
];
for (const [name, scores, want] of cases) {
test(name, () => {
assert.deepEqual(scoreLines(scores), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
// Package scorelines walks the entries and the values of a map.
package scorelines
import (
"maps"
"slices"
"strconv"
)
// ScoreLines returns a line key=value for each entry in ascending order of
// the key, then the line total=N with the sum of the values.
func ScoreLines(scores map[string]int) []string {
lines := make([]string, 0, len(scores)+1)
// The order of a range over a map is not specified, so sort the keys.
for _, k := range slices.Sorted(maps.Keys(scores)) {
lines = append(lines, k+"="+strconv.Itoa(scores[k]))
}
total := 0
for _, v := range scores {
total += v
}
return append(lines, "total="+strconv.Itoa(total))
}
score_lines_test.go 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
package scorelines
import (
"slices"
"testing"
)
var cases = []struct {
name string
scores map[string]int
want []string
}{
{"scores", map[string]int{"bob": 7, "amy": 9, "cal": 4}, []string{"amy=9", "bob=7", "cal=4", "total=20"}},
{"one", map[string]int{"x": 1}, []string{"x=1", "total=1"}},
{"empty", map[string]int{}, []string{"total=0"}},
{"case", map[string]int{"b": 1, "B": 2, "a": 3, "A": 4}, []string{"A=4", "B=2", "a=3", "b=1", "total=10"}},
{"negative", map[string]int{"a": -5, "b": 5}, []string{"a=-5", "b=5", "total=0"}},
{"prefix", map[string]int{"abc": 3, "a": 2, "ab": 1}, []string{"a=2", "ab=1", "abc=3", "total=6"}},
{"reverse", map[string]int{"j": 1, "i": 2, "h": 3, "g": 4, "f": 5, "e": 6, "d": 7, "c": 8, "b": 9, "a": 10}, []string{"a=10", "b=9", "c=8", "d=7", "e=6", "f=5", "g=4", "h=3", "i=2", "j=1", "total=55"}},
}
func TestScoreLines(t *testing.T) {
for _, c := range cases {
if got := ScoreLines(c.scores); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
use std::collections::HashMap;
/// Returns a line key=value for each entry in key order, then the total of the values.
pub fn score_lines(scores: &HashMap<&str, i32>) -> Vec<String> {
// A HashMap gives its entries in arbitrary order, so sort them.
let mut entries: Vec<(&&str, &i32)> = scores.iter().collect();
entries.sort();
let mut lines: Vec<String> = entries.iter().map(|(k, v)| format!("{k}={v}")).collect();
let total: i32 = scores.values().sum();
lines.push(format!("total={total}"));
lines
}
tests/score_lines_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/iterate-over-a-map/.
use std::collections::HashMap;
use algo_iterate_over_a_map::score_lines;
#[test]
fn cases() {
let cases: Vec<(&str, Vec<(&str, i32)>, Vec<&str>)> = vec![
("scores", vec![("bob", 7), ("amy", 9), ("cal", 4)], vec!["amy=9", "bob=7", "cal=4", "total=20"]),
("one", vec![("x", 1)], vec!["x=1", "total=1"]),
("empty", vec![], vec!["total=0"]),
("case", vec![("b", 1), ("B", 2), ("a", 3), ("A", 4)], vec!["A=4", "B=2", "a=3", "b=1", "total=10"]),
("negative", vec![("a", -5), ("b", 5)], vec!["a=-5", "b=5", "total=0"]),
("prefix", vec![("abc", 3), ("a", 2), ("ab", 1)], vec!["a=2", "ab=1", "abc=3", "total=6"]),
("reverse", vec![("j", 1), ("i", 2), ("h", 3), ("g", 4), ("f", 5), ("e", 6), ("d", 7), ("c", 8), ("b", 9), ("a", 10)], vec!["a=10", "b=9", "c=8", "d=7", "e=6", "f=5", "g=4", "h=3", "i=2", "j=1", "total=55"]),
];
for (name, entries, want) in cases {
let scores: HashMap<&str, i32> = entries.into_iter().collect();
assert_eq!(score_lines(&scores), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-over-a-map/.
# score_lines KEY=VALUE...
# Puts the pairs in an associative array, then prints one line KEY=VALUE for
# each entry in ascending order of the key by its bytes, then total=N with the
# sum of the values.
score_lines() {
local -A map=()
local arg key total=0
for arg in "$@"; do
map[${arg%%=*}]=${arg#*=}
done
# "${!map[@]}" gives the keys, one word each, in no set order.
for key in "${!map[@]}"; do
printf '%s=%s\n' "$key" "${map[$key]}"
done | LC_ALL=C sort
# "${map[@]}" gives the values.
for arg in "${map[@]}"; do
total=$((total + arg))
done
printf 'total=%d\n' "$total"
}
test_score_lines.bats 27 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/iterate-over-a-map/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/score_lines.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=$(score_lines "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "scores" { check "amy=9\nbob=7\ncal=4\ntotal=20\n" bob=7 amy=9 cal=4; }
@test "one" { check "x=1\ntotal=1\n" x=1; }
@test "empty" { check "total=0\n"; }
@test "case" { check "A=4\nB=2\na=3\nb=1\ntotal=10\n" b=1 B=2 a=3 A=4; }
@test "negative" { check "a=-5\nb=5\ntotal=0\n" a=-5 b=5; }
@test "prefix" { check "a=2\nab=1\nabc=3\ntotal=6\n" abc=3 a=2 ab=1; }
@test "reverse" { check "a=10\nb=9\nc=8\nd=7\ne=6\nf=5\ng=4\nh=3\ni=2\nj=1\ntotal=55\n" j=1 i=2 h=3 g=4 f=5 e=6 d=7 c=8 b=9 a=10; }
References
- The Python Standard Library, Built-in Types, Dictionary view objects
- MDN Web Docs, Map, Key order
- The Go Programming Language Specification, For statements with range clause
- Rust standard library, struct HashMap, iter; retain
- .NET API reference, Dictionary<TKey,TValue> class, Remarks
- MDN Web Docs, for...in, Description, Iteration order
- Java SE 25 API, Interface Map, keySet()
- Java SE 25 API, Class ConcurrentModificationException, Description
- cppreference.com, std::unordered_map::erase, Description; Return value
- POSIX.1-2024, tdelete, tfind, tsearch, twalk, DESCRIPTION; APPLICATION USAGE
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 1JP4KA Edit this page History Report an error Markdown