awelgorithms

Create a hash map

Updated

A hash map stores key → value pairs. Creating one means starting empty: no keys, size 0. You put pairs later. Empty is a real map, not a missing structure.

What to focus on

We write {4:2} for key 4 maps to value 2. Empty is {}. Keys are unique. After creation there is no legal get-without-default until you put something.

Worked examples

empty

a = []
  1. allocate an empty map
  2. no keys

Result: {} · size 0

one pair

a = [4], value 2
  1. put 4→2

Result: {4:2} · size 1

three pairs

a = [4, 1, 9], values 2, 8, 3
  1. put 4→2, 1→8, 9→3

Result: {4:2, 1:8, 9:3} · size 3

Try it

Write create(). No arguments. Return the map after the listed puts. Do not print. The key names the slot. The value lives in that slot. a = [] → {} · size 0. a = [4], value 2 → {4:2} · size 1. a = [4, 1, 9], values 2, 8, 3 → {4:2, 1:8, 9:3} · size 3.

keys and values are integers. Creating {} is allowed.