# 3.6 Dictionaries

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

Web page: https://pseudolearn.app/en/spec/tipos/diccionarios

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

## 3.6.1 How to write it

```pseudolearn
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.

### Program: An address book of ages

```pseudolearn
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**

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

*The program finishes normally.*

**Figure 3.6-1: Keys pointing to values**

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.

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

## 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`.

### Program: Asking before reading

```pseudolearn
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**

```text
no está
```

*The program finishes normally.*

> **Limit**
>
> - Allowed keys: `Integer`, `Character`, `String`, `Boolean` or an enumeration. Strings are compared character by character, without normalising.
> - It is a shared reference, like a vector, with the same memory limits.
> - `remove(key)` returns `Some(value)` if it removed it or `None` if it was not there; removing and inserting again places the key at the end.

> **Common mistakes**
>
> Reading a missing key stops the program:
>
> ### Program: A key that is not there
>
> ```pseudolearn
> Algorithm Ausente
>   Define d As Dictionary<String, Integer> <- dictionary();
>   Write d["nadie"];
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `missingDictionaryKey` (error, 3:9): The key does not exist in the dictionary
>
> *The program finishes with an error.*
>
> And not every type works as a key:
>
> ### Program: A real key
>
> ```pseudolearn
> Algorithm ClaveReal
>   Define d As Dictionary<Real, Integer>;
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `invalidDictionaryKeyType` (error, 2:15): The dictionary key type is not allowed
>
> *The program finishes with an error.*

> **Under the hood**
>
> The engine keeps the entries in order in a list and maintains a separate hash index to find them quickly. When it grows or accumulates gaps from removals, it reorganises the index without changing the order of the entries. That is why the output order does not depend on the machine.
>
> **Intermediate representation**
>
> ```text
> module Buscar en
> class "$dictionary<string,integer>" { "$key": str, "$leaf:value": i64 }
> func suspendible @main() -> unit {
> b0() mass 3:
>   stmt.enter @2:3-2:63
>   %0 = collection.new obj<"$dictionary<string,integer>"> @2:51-2:63
>   stmt.exit @2:3-2:63
>   stmt.enter @3:3-3:22
>   %1 = const.str "Ana" @3:10-3:15
>   %2 = const.i64 12 @3:20-3:22
>   collection.store %0, %1, %2 @3:3-3:22
>   stmt.exit @3:3-3:22
>   stmt.enter @4:3-7:12
>   %3 = const.str "Eva" @4:22-4:27
>   %4 = collection.lookup %0, %3 @4:10-4:28
>   %5 = const.i64 0
>   %6 = int.cmp ge, %4, %5 @4:10-4:28
>   branch %6, b1(), b2()
> b1() mass 0:
>   %7 = collection.load i64, %0, %4, 0 @4:10-4:28
>   %8 = const.i64 0
>   %9 = const.i64 1
>   %10 = value.reinterpret i64, %7
>   jump b3(%9, %10)
> b2() mass 0:
>   %11 = const.i64 0
>   %12 = const.i64 0
>   jump b3(%12, %11)
> b3(%13: i64, %14: i64) mass 0:
>   %15 = const.i64 1 @5:5-5:15
>   %16 = int.cmp eq, %13, %15
>   branch %16, b6(), b8()
> b4() mass 0:
>   stmt.exit @4:3-7:12
>   return @8:1-8:13
> b5() mass 0:
>   decide.none @4:3-7:12
>   jump b4()
> b6() mass 2:
>   %17 = const.i64 0
>   decide.case %17 @4:3-7:12
>   stmt.enter @5:5-5:15
>   %18 = value.reinterpret i64, %14
>   stmt.exit @5:5-5:15
>   stmt.enter @5:17-5:37
>   %19 = const.str "tiene " @5:23-5:31
>   out.write %19, %18, newline @5:17-5:37
>   stmt.exit @5:17-5:37
>   jump b4()
> b7() mass 1:
>   %20 = const.i64 1
>   decide.case %20 @4:3-7:12
>   stmt.enter @6:11-6:26
>   %21 = const.str "no está" @6:17-6:26
>   out.write %21, newline @6:11-6:26
>   stmt.exit @6:11-6:26
>   jump b4()
> b8() mass 0:
>   %22 = const.i64 0 @6:5-6:9
>   %23 = int.cmp eq, %13, %22
>   branch %23, b7(), b9()
> b9() mass 0:
>   jump b5()
> }
> ```

**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.

**See also**
- [3.5 Vectors](https://pseudolearn.app/en/spec/tipos/vectores.md)
- [3.10 Optional and Result](https://pseudolearn.app/en/spec/tipos/opcional-resultado.md)
- [6.2 Multiple selection with Switch](https://pseudolearn.app/en/spec/control/segun.md)
