Sub topic 2
Why Some Objects Can Be Keys and Others Cannot
Assume you know variables, loops, functions, and basic Python types. This chapter focuses on how hashability affects dictionaries, sets, and lookup speed.
Why Some Objects Can Be Keys and Others Cannot
A hashable object has a hash value that stays stable during its lifetime. Python uses this value to place and find dictionary keys and set elements. The object must also have consistent equality behavior.
Immutable values such as strings, integers, and tuples of hashable values are usually hashable. Lists and dictionaries are mutable, so they are not hashable. A tuple is hashable only when every item inside it is hashable.
locations = {(1, 2): "office"}
print(locations[(1, 2)])
try:
locations[[1, 2]] = "invalid"
except TypeError as error:
print(error) # unhashable type: 'list'
tags = {("python", "beginner"), ("python", "data")}
print(tags)A frozenset is an immutable set, so it can be used as a dictionary key or as an element of another set.
Dictionaries: Looking Things Up by Key
A dictionary maps each unique key to a value. Use square brackets when a missing key should raise KeyError. Use get when a default is more convenient.
users = {"ana": 31, "ben": 27}
print(users["ana"])
print(users.get("cy", 0))
users["cy"] = 45
print("cy" in users)Sets: Uniqueness and Set Operations
A set stores unique hashable elements. It supports intersection (&), union (|), and difference (-). Convert to sorted when predictable display order matters.
a = {1, 2, 3}
b = {2, 3, 4}
print(sorted(a & b)) # [2, 3]
print(sorted(a | b)) # [1, 2, 3, 4]
print(sorted(a - b)) # [1]How Fast Is Lookup?
These are typical average costs, not guarantees for every input.
| Operation | List or tuple | Dict or set |
|---|---|---|
| Membership test with `in` | O(n) | O(1) average |
| Key or element lookup | Indexing: O(1) | O(1) average |
Lists and tuples scan items for membership. Dictionaries and sets use hashing. Hash collisions or unusual inputs can make hash-based operations slower, but average lookup remains constant time.
Exercise
Which collection should store unique usernames for fast membership tests, and why?
Show answer
Use a set. Usernames are unique elements, and hash-based membership tests are O(1) on average.