Skip to content

Commit 4224b87

Browse files
Update README.md
1 parent 7771703 commit 4224b87

1 file changed

Lines changed: 0 additions & 50 deletions

File tree

README.md

Lines changed: 0 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -2341,56 +2341,6 @@ print(list(cache._cache.keys())) # ['c', 'a', 'd']
23412341

23422342
**No.** Dictionary keys must be **hashable**, and all mutable built-in types (`list`, `dict`, `set`) are **not hashable**. Attempting to use them raises `TypeError`.
23432343

2344-
```py
2345-
# Mutable types — NOT hashable, cannot be dict keys
2346-
try:
2347-
d = {[1, 2, 3]: "value"} # list key
2348-
except TypeError as e:
2349-
print(f"TypeError: {e}") # unhashable type: 'list'
2350-
2351-
try:
2352-
d = {{1: "a"}: "value"} # dict key
2353-
except TypeError as e:
2354-
print(f"TypeError: {e}") # unhashable type: 'dict'
2355-
2356-
# Immutable types — hashable, valid dict keys
2357-
valid_keys = {
2358-
"string": 1,
2359-
42: 2,
2360-
3.14: 3,
2361-
True: 4,
2362-
(1, 2, 3): 5, # tuple of immutables — hashable
2363-
frozenset({1, 2}): 6, # frozenset — hashable
2364-
}
2365-
print(valid_keys[(1, 2, 3)]) # 5
2366-
2367-
# A tuple is only hashable if ALL its elements are hashable
2368-
try:
2369-
d = {(1, [2, 3]): "value"} # tuple containing a list
2370-
except TypeError as e:
2371-
print(f"TypeError: {e}") # unhashable type: 'list'
2372-
2373-
# Making a custom object hashable
2374-
class Point:
2375-
def __init__(self, x: float, y: float) -> None:
2376-
self.x, self.y = x, y
2377-
2378-
def __eq__(self, other: object) -> bool:
2379-
if not isinstance(other, Point): return NotImplemented
2380-
return self.x == other.x and self.y == other.y
2381-
2382-
def __hash__(self) -> int:
2383-
return hash((self.x, self.y)) # hash based on immutable tuple
2384-
2385-
grid: dict[Point, str] = {}
2386-
grid[Point(0, 0)] = "origin"
2387-
grid[Point(1, 2)] = "marker"
2388-
print(grid[Point(0, 0)]) # origin
2389-
2390-
# Rule: if __eq__ is defined, __hash__ MUST also be defined
2391-
# Python sets __hash__ = None if __eq__ is defined without __hash__
2392-
```
2393-
23942344
**Rule:** Hashable = immutable structure + consistent `__hash__`. `hash(x) == hash(y)` whenever `x == y`.
23952345

23962346
**Use Case:** A graph algorithm caches computed shortest paths using `frozenset({source, destination})` as a dict key — symmetric pairs `(A→B)` and `(B→A)` map to the same cache entry, halving cache misses.

0 commit comments

Comments
 (0)