Computer Science
Why?
Why Can't a List Be a Dictionary Key?
Why can't you use a Python list as a dictionary key?
Quick check · tap an answer to continue
Lesson notes
Key points
- Because a dictionary stores each key in the bucket chosen by the key's hash at insertion time.
- Because a list is mutable, appending to it after insertion would change its hash value.
- Because a changed hash sends future lookups to a different bucket, the stored entry would become unreachable.
Definitions
- Hashable
- An object whose hash never changes in its lifetime and that can be compared for equality.
Takeaway: So keys must be hashable: use immutable types like tuples or strings.
Quick check: What property must a dictionary key's hash have over time?
- It must grow
- It must stay constant
- It must be prime
A changing hash would send lookups to the wrong bucket.
Hash picks bucketMutabilityLost entry
Lessons like this, for your syllabus.
Short narrated study videos written for your course, level and exam. Free to start.
Get lessons for your own syllabus