Command Palette

Search for a command to run...

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

Hashable and unhashable values

The last line ends with an error on purpose. Read the message: it names the type that cannot be hashed.

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?

Hashable and unhashable values
Sign in to run this example in your browser.

Expected output

hash(42): 42
1, 1.0 and True share a hash: True
equal tuples, equal hashes: True
equal strings, equal hashes: True
one key, last value wins: {1: 'yes'}
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    hash([1, 2])
    ~~~~^^^^^^^^
TypeError: unhashable type: 'list'