# The Front Desk Finds You in One Scan: Dictionaries

Find any of a gym's 2,000 members in one step, 600 times an hour, with the dictionary your language already has: add, read, update and remove entries, read a missing key safely, and know when not to count on its order.

Apprentice · Data Structures · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Add, read, update and remove entries in your language's dictionary, and read a missing key safely
- Explain why a dictionary's order isn't something to rely on, and sort its keys when order matters

## Key takeaways

- Searching a list of members at every scan is O(n); a hash table makes each scan O(1) on average, and every language has one built in, so you don't write your own.
- A dictionary stores values under keys. C#'s Dictionary, Java's HashMap, Python's dict and JavaScript's Map are all hash tables.
- Adding, reading, updating, removing and checking for a key are all O(1) on average.
- Reading a key that isn't there is an error in C# and Python, and gives null or undefined in Java and JavaScript, so check first or use a default value.
- A dictionary doesn't promise an order you can count on in every language, so sort the keys when order matters.

**Before this:** *Exercise: Build a Coat Check*, where a hash table you wrote yourself took about 50 lines (collisions and moving day included), and stored only coats under names.

The gym on Maple Street opens at 6 a.m., and by 7 the line at the front desk reaches the door. Between 7 and 8, about 600 members scan their cards, one every six seconds. Each scan gives the app the member's name, and the screen at the turnstile should show "Welcome back, Maya: visit 13 this month" before she's through. The gym has 2,000 members, and the app keeps them in a list.

It's the job behind user sessions found by their ID, a cart's prices found by product code, and settings found by their name: any time you'd otherwise write "loop through the list until you find it". This lesson finds the member in one step, without writing a hash table again.

## What would you try?

**Search the list, as the app does now.** Each scan reads members from the top until the name matches: about 1,000 on average, and all 2,000 for someone who isn't a member. That's O(n) per scan, about 600,000 name checks in the 7 a.m. hour. A computer can do that today. But the gym is opening a second branch and expects 20,000 members, and then every scan does ten times the work, at the busiest hour of the day.

**Keep the list in A to Z order, and halve it.** Now a scan takes about 11 looks for 2,000 members, and 15 for 20,000: O(log n), *One Song in a Million, in 20 Looks: Binary Search* from Module 4. But members don't join in A to Z order. On a busy January day 40 people sign up, and each one slides every name after theirs along one place, O(n) per sign-up. It's the coat check's A to Z rack again: finding got fast, adding got slow.

**Write a hash table, as you did for the coat check.** Each scan works out one bucket from the name: O(1) on average, for 2,000 members or 20,000. It works. But it's 50 lines to write and test, collisions and moving day included, and it stores coats under names. Visits under names, prices under product codes and sessions under IDs would each want their own, or a careful rewrite.

| What we tried | Find a member | Add a member | Where it breaks |
|---|---|---|---|
| A list | O(n): about 1,000 looks | O(1) | 20,000 members at 7 a.m. |
| An A to Z list | O(log n): about 11 looks | O(n): slide the names after it | busy sign-up days |
| A hash table you write | O(1) on average | O(1) on average | 50 lines to write and test, for every new job |

## The questions that lead to it

**What does the front desk do most?** Find a member by their name, 600 times an hour, and add 1 to their visits. New members join every day. Nobody at the desk needs the members in A to Z order. That's the coat check's job exactly, so a hash table is the right structure.

**So what's left?** Only the question the coat check raised: do you have to build one every time? You don't. Storing values under keys is so common that every language comes with a hash table built in, written once, tested by millions of programs, and ready for any kind of key and value.

## How it got its name

Built-in hash tables usually go by a friendlier name: a **dictionary**. It works like a paper dictionary: you look up a word, the key, and find what's stored under it, its definition, the value. Each language calls its own something different, but they all work the way the coat check did:

| Language | The dictionary | Made with |
|---|---|---|
| C# | `Dictionary<TKey, TValue>` | `new Dictionary<string, int>()` |
| Java | `HashMap<K, V>` (a kind of `Map`) | `new HashMap<>()` |
| Python | `dict` | `{}` |
| JavaScript and TypeScript | `Map` | `new Map()` |

Java and JavaScript call it a **map**, because it maps each key to its value. The two types in angle brackets are the key's type and the value's type: `Dictionary<string, int>` has text keys and whole-number values.

## The everyday jobs

Here is the front desk's dictionary: each member's name and their visits this month. The code reads a value, updates one when Leo scans his card, checks for a key, reads a key that might be missing, and removes one:

```csharp
Dictionary<string, int> visits = new Dictionary<string, int>();
visits["Maya"] = 12;
visits["Leo"] = 3;
visits["Priya"] = 8;

Console.WriteLine("Members: " + visits.Count);
Console.WriteLine("Maya's visits: " + visits["Maya"]);

visits["Leo"] = visits["Leo"] + 1;
Console.WriteLine("Leo's visits: " + visits["Leo"]);

Console.WriteLine("Is Sam a member? " + (visits.ContainsKey("Sam") ? "yes" : "no"));
Console.WriteLine("Sam's visits: " + visits.GetValueOrDefault("Sam", 0));

visits.Remove("Priya");
Console.WriteLine("Members after Priya cancels: " + visits.Count);
```

```text
Members: 3
Maya's visits: 12
Leo's visits: 4
Is Sam a member? no
Sam's visits: 0
Members after Priya cancels: 2
```

```java
void main() {
    Map<String, Integer> visits = new HashMap<>();
    visits.put("Maya", 12);
    visits.put("Leo", 3);
    visits.put("Priya", 8);

    IO.println("Members: " + visits.size());
    IO.println("Maya's visits: " + visits.get("Maya"));

    visits.put("Leo", visits.get("Leo") + 1);
    IO.println("Leo's visits: " + visits.get("Leo"));

    IO.println("Is Sam a member? " + (visits.containsKey("Sam") ? "yes" : "no"));
    IO.println("Sam's visits: " + visits.getOrDefault("Sam", 0));

    visits.remove("Priya");
    IO.println("Members after Priya cancels: " + visits.size());
}
```

```text
Members: 3
Maya's visits: 12
Leo's visits: 4
Is Sam a member? no
Sam's visits: 0
Members after Priya cancels: 2
```

```python
visits = {}
visits["Maya"] = 12
visits["Leo"] = 3
visits["Priya"] = 8

print(f"Members: {len(visits)}")
print(f"Maya's visits: {visits['Maya']}")

visits["Leo"] = visits["Leo"] + 1
print(f"Leo's visits: {visits['Leo']}")

print(f"Is Sam a member? {'yes' if 'Sam' in visits else 'no'}")
print(f"Sam's visits: {visits.get('Sam', 0)}")

del visits["Priya"]
print(f"Members after Priya cancels: {len(visits)}")
```

```text
Members: 3
Maya's visits: 12
Leo's visits: 4
Is Sam a member? no
Sam's visits: 0
Members after Priya cancels: 2
```

```javascript
const visits = new Map();
visits.set("Maya", 12);
visits.set("Leo", 3);
visits.set("Priya", 8);

console.log(`Members: ${visits.size}`);
console.log(`Maya's visits: ${visits.get("Maya")}`);

visits.set("Leo", visits.get("Leo") + 1);
console.log(`Leo's visits: ${visits.get("Leo")}`);

console.log(`Is Sam a member? ${visits.has("Sam") ? "yes" : "no"}`);
console.log(`Sam's visits: ${visits.get("Sam") ?? 0}`);

visits.delete("Priya");
console.log(`Members after Priya cancels: ${visits.size}`);
```

```text
Members: 3
Maya's visits: 12
Leo's visits: 4
Is Sam a member? no
Sam's visits: 0
Members after Priya cancels: 2
```

```typescript
const visits = new Map<string, number>();
visits.set("Maya", 12);
visits.set("Leo", 3);
visits.set("Priya", 8);

console.log(`Members: ${visits.size}`);
console.log(`Maya's visits: ${visits.get("Maya")}`);

visits.set("Leo", (visits.get("Leo") ?? 0) + 1);
console.log(`Leo's visits: ${visits.get("Leo")}`);

console.log(`Is Sam a member? ${visits.has("Sam") ? "yes" : "no"}`);
console.log(`Sam's visits: ${visits.get("Sam") ?? 0}`);

visits.delete("Priya");
console.log(`Members after Priya cancels: ${visits.size}`);
```

```text
Members: 3
Maya's visits: 12
Leo's visits: 4
Is Sam a member? no
Sam's visits: 0
Members after Priya cancels: 2
```

Setting a key that's already there replaces its value: keys are unique, just as a name was never on two hooks at the coat check.

**Where the languages differ: a missing key.** Reading a key that isn't there with square brackets stops a C# program with a `KeyNotFoundException`, and a Python program with a `KeyError`. Java's `get` gives `null`, and JavaScript's gives `undefined`. That's why TypeScript makes you say what happens when Leo isn't there (`?? 0`), and why every language has a safe way to read: `GetValueOrDefault` (C#), `getOrDefault` (Java), `get(key, default)` (Python) and `get(key) ?? default` (JavaScript and TypeScript). When a key might be missing, check for it first or give a default.

JavaScript code also uses plain objects (`{ Maya: 12 }`) as dictionaries. They work for text keys; `Map` takes keys of any type and is the hash table this course uses.

## Order: don't count on it

Print every member with a loop, and in Python or JavaScript you'll see them in the order they were added. Java's `HashMap` may print them in any order, the order of its buckets. C#'s `Dictionary` usually keeps the order they were added, but doesn't promise it once keys are removed. A hash table puts keys where the recipe says, not in a line.

So when the order matters, for a report, a screen, or a test, sort the keys first:

```csharp
Dictionary<string, int> visits = new Dictionary<string, int> { ["Priya"] = 8, ["Maya"] = 12, ["Leo"] = 4 };

List<string> names = new List<string>(visits.Keys);
names.Sort();
foreach (string name in names)
{
    Console.WriteLine(name + ": " + visits[name]);
}
```

```text
Leo: 4
Maya: 12
Priya: 8
```

```java
void main() {
    Map<String, Integer> visits = new HashMap<>(Map.of("Priya", 8, "Maya", 12, "Leo", 4));

    List<String> names = new ArrayList<>(visits.keySet());
    Collections.sort(names);
    for (String name : names) {
        IO.println(name + ": " + visits.get(name));
    }
}
```

```text
Leo: 4
Maya: 12
Priya: 8
```

```python
visits = {"Priya": 8, "Maya": 12, "Leo": 4}

for name in sorted(visits):
    print(f"{name}: {visits[name]}")
```

```text
Leo: 4
Maya: 12
Priya: 8
```

```javascript
const visits = new Map([["Priya", 8], ["Maya", 12], ["Leo", 4]]);

for (const name of [...visits.keys()].sort()) {
  console.log(`${name}: ${visits.get(name)}`);
}
```

```text
Leo: 4
Maya: 12
Priya: 8
```

```typescript
const visits = new Map<string, number>([["Priya", 8], ["Maya", 12], ["Leo", 4]]);

for (const name of [...visits.keys()].sort()) {
  console.log(`${name}: ${visits.get(name)}`);
}
```

```text
Leo: 4
Maya: 12
Priya: 8
```

Sorting costs O(n log n), so it's worth doing only when you need the order. Java has two cousins of `HashMap` for this: `LinkedHashMap` keeps the order keys were added, and `TreeMap` keeps them sorted. C#'s `SortedDictionary` keeps keys sorted too. Python and JavaScript have no sorted dictionary built in; sorting the keys is the way.

## The cost card

| Operation | Big-O | The everyday reason |
|---|---|---|
| Add or update a key's value | O(1) on average | Hash the key, go to its bucket |
| Read a key's value | O(1) on average | Hash the key, go straight to it |
| Check whether a key is there | O(1) on average | Same trip, without taking anything |
| Remove a key | O(1) on average | Same trip, take it off |
| Loop over every entry | O(n) | Every entry is visited once |
| List the keys in order | O(n log n) | The buckets aren't in order, so sort first |
| Find a key from its value | O(n) | The hash works from keys, so check every entry |

**When something else wins.** For a handful of items, a plain list is fine: reading 20 names takes no time, and a list keeps them in the order they were added. And when the job done most is showing everyone in A to Z order, with few changes, a sorted list or one of the sorted dictionaries above earns its place. For finding by a key, again and again, while new keys arrive, the dictionary wins.

## Check yourself

2 questions to try on the lesson page.

## So what

When you catch yourself looping through a list to find something by its name or ID, a dictionary is usually the fix: one line to build, and every lookup after that is O(1) on average. It's the coat check you built, already written, tested and waiting in your language.

## Key terms

- [Dictionary](https://www.ask-codey.com/glossary/dictionary-data-structures)
- [Dictionary&lt;TKey, TValue>](https://www.ask-codey.com/glossary/dictionary-tkey-tvalue)
- [HashMap](https://www.ask-codey.com/glossary/hashmap)
- [Dictionary](https://www.ask-codey.com/glossary/dictionary)
- [Map](https://www.ask-codey.com/glossary/map-javascript-2)

## Cheat sheets

- [The Front Desk Finds You in One Scan: Dictionaries](https://www.ask-codey.com/cheat-sheets/ds-dictionaries-cheat-sheet)

Source: https://www.ask-codey.com/lessons/ds-dictionaries
