Dunder Quest Play

Stage 2 · Cinder Span

Dictionaries & Hashing

“Every key knows its bucket. Do you?”Cinder Warlock

Scrolls on the trail

These are the 5 lore scrolls you'll find in Cinder Span, in the order the lesson teaches them. The comment after each print shows what it outputs.

Lore scroll · Dictionaries & Hashing

Keys and Values

bag = {"ash": 3, "ember": 5}
print(bag["ember"])  # 5
bag["clay"] = 1
print(len(bag))  # 3

A dict maps each key to a value. You look things up by key, not by position.

Lore scroll · Dictionaries & Hashing

The Hashing Rune

key = "ember"
slot = hash(key) % 4
print(slot == hash(key) % 4)  # True

A dict hashes the key to pick a bucket, then looks only there. No searching.

Lore scroll · Dictionaries & Hashing

One Key, One Value

d = {}
d["ash"] = 1
d["ash"] = 2
print(d, len(d))  # {'ash': 2} 1

The same key always hashes to the same bucket, so writing it again replaces the value.

Lore scroll · Dictionaries & Hashing

Keys Must Not Change

ok = {(1, 2): "tuple"}
print(ok[(1, 2)])  # tuple
bad = {[1, 2]: "list"}  # TypeError!

A list can change, so its hash could not be trusted. Keys must be str, int, tuple...

This code stops with TypeError, and that error is the point of the scroll.

Lore scroll · Dictionaries & Hashing

Asking Politely

bag = {"ash": 3}
print(bag.get("clay", 0))  # 0
print("ash" in bag)  # True

bag["clay"] would raise KeyError. get() hands back a default instead.

The stage puzzle: The hash vault

In-game view of The hash vault in Cinder Span

Two rune keys, "ash" and "ember", lie on the route. Near the end a vault door has one lock per key and four bucket blocks numbered 0 to 3. Store each key by bumping the bucket it hashes to. The vault's rune hash adds up the letter codes of the key (ord in Python), then % 4 picks the bucket.

Slate in the stage
bucket = rune_hash(key) % 4
Show the answer

"ash" is 97 + 115 + 104 = 316, and 316 % 4 is 0. "ember" adds up to 523, and 523 % 4 is 3.

Practice the Cinder Warlock's trial

In the game, the Cinder Warlock duels you in a sealed arena. His question shows across the top of the screen, and you answer by jumping up into the lettered block, A to D, while you dodge his spells. You need 3 right answers to banish him. These are his questions, drawn from all 9 in his bank. The hints work the same as in the game: ask once for his riddle, and ask again for him to rule out a wrong answer.