Command Palette

Search for a command to run...

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

Equal objects need equal hashes

Classes are taught in Phase 8. For now see the result: two different Point objects that are equal work as the same dictionary key.

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?

Equal objects need equal hashes
Sign in to run this example in your browser.

Expected output

a == b: True | same object: False
lookup with b: home
distinct keys: 1