Skip to content

SpecificationIII · Types and values

3.6

Dictionaries

A dictionary stores key-value pairs: you look up by the key and get the value, like in a phone book.

Markdown version

3.6.1 How to write it

Define «name» As dictionary<«key type», «value type»> <- dictionary();
«name»[«key»] <- «value»;
«name»[«key»]
«name».find(«key»)

3.6.2 How it works

Writing d[k] <- v stores the value v under the key k: if the key did not exist, it is added at the end; if it already existed, its value is replaced without moving it. Reading d[k] returns the value of that key. Dictionaries remember insertion order: when written or when their keys are requested, they come out in the order they were added.

ProgramAn address book of ages

Algorithm Edades
  Define edades As Dictionary<String, Integer> <- dictionary();
  edades["Ana"] <- 12;
  edades["Luis"] <- 11;
  edades["Ana"] <- 13;
  Write edades, " ", edades.length();
  Write edades["Ana"], " ", edades.keys();
EndAlgorithm

Output

{"Ana": 13, "Luis": 11} 2
13 ["Ana", "Luis"]

The program finishes normally.

Figure 3.6-1.Each key points to a value. Replacing the value of a key does not move it from its place.

Two columns, keys and values. The key Ana points to the value 13, marked as replaced; the key Luis points to 11. A note explains that keys keep the order in which they were inserted.

3.6.3 Looking up without failing

Reading a key that does not exist is a failure. When you do not know whether it is there, use find: it returns Some(value) or None, and you handle it with Switch.

ProgramAsking before reading

Algorithm Buscar
  Define edades As Dictionary<String, Integer> <- dictionary();
  edades["Ana"] <- 12;
  Switch edades.find("Eva") Do
    Some(edad): Write "tiene ", edad;
    None: Write "no está";
  EndSwitch
EndAlgorithm

Output

no está

The program finishes normally.

In short

  • A dictionary associates keys with values.
  • d[k] <- v inserts or replaces; d[k] reads and fails if the key is missing.
  • find returns Some or None and never fails.
  • It keeps insertion order.