3 ms·
nope. Here I use the trick that for most ints, hash(i) == i to quickly find two values with the same hash and put them in a dict. >>> k1 = "foo" >>> k
by jepler 11y ago
nope. Here I use the trick that for most ints, hash(i) == i to quickly find two values with the same hash and put them in a dict.
>>> k1 = "foo"
>>> k2 = hash(k1)
>>> hash(k1) == hash(k2)
True
>>> d = {k1: "v1", k2: "v2"}
>>> d[k1]
'v1'
>>> d[k2]
'v2'
Now that I've been pedantic, I hope I get this right: in Python, it is equality (==) that defines same-ness for dicts and sets. But if x == y, then you have to ensure that hash(x) == hash(y). Python uses this characteristic to make the initial check for dict and set membership integer comparisons on the hash, but when two items have the same hash, Python goes on to distinguish them on the basis of equality.
- rspeer 11y agoOh, while we're talking about things with predictable hashes, here's a Python WTF that I enjoy: class A: def __hash__(self): return -1 print(hash(A())) Prints -2. For the same reason, if you ever need an easy hash collision, use the hashes of -1 and -2.
- rspeer 11y agoI'll explain the reason, BTW: a hash value of -1 isn't valid in CPython because that integer is reserved as a flag value. So any hash method that returns -1 quietly gets its value changed to -2.