Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.5 — How Dictionaries Work: Hashing
Python · Example 4 of 4

A stable cache key for a prompt

hash("text") changes on every run, so it is the wrong tool for a cache that is saved to disk. hashlib.sha256 gives the same fingerprint everywhere, every time. (.encode("utf-8") turns text into bytes, which is what sha256 reads; Topic 6.1 teaches the import.)

A dictionary turns each key into a number called a hash, and uses that number to jump straight to a slot in a table, so lookup takes about the same time however big the dictionary is. This is why keys must be hashable (unchanging) and why a list cannot be a key.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Create d = {1: "int", 1.0: "float", True: "bool"} and print it and its length. Explain why the length is not 3.

02

Make a dictionary that maps grid coordinates to names: (0, 0) is "start" and (2, 3) is "exit". Print the name at (2, 3).

03

Write a loop that puts the numbers 10, 17, 25, 33 into a table of 5 slots (lists) using number % 5, then print the table.

Explain it without notes

01

Why is dictionary lookup O(1) on average?

02

Why can't a list be a dictionary key, but a tuple can?

03

What is a hash collision, and how does Python handle it?

04

If you define __eq__ on a class, why should you also define __hash__?

05

Is dictionary lookup always O(1)? What could make it slow, and what does Python do about it?

A stable cache key for a prompt
Sign in to run this example in your browser.

Expected output

fingerprint: 82d3e453ffb434b6 | length: 64
same prompt, cache hit: True
different prompt, cache hit: False