I'm curious about how the dictionary key is garanteed as unique in Python. Via hash value? via ==
? or via is
?
I have defined a class Postition
with new init and eq methods.
class Position():
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
return self.x == other.x and self.y == other.y
Then, two instances p1
and p2
are created and I've checked something as following:
p1 = Position(1,2)
p2 = Position(1,2)
print(f"Hash values are equal: {hash(p1) == hash(p2)}")
d = {p1:2}
d[p2] = 4
print(f"Length of d is {len(d)}")
print(f"d[p1]={d[p1]}")
print(f"d[p2]={d[p2]}")
for key in d.keys():
print(f"The memory adress of key is {id(key)}")
print(f"The memory adress of p1 is {id(p1)}")
print(f"The memory adress of p2 is {id(p2)}")
This gives the result:
Hash values are equal: True
Length of d is 1
d[p1]=4
d[p2]=4
The memory adress of key is 2184620745864
The memory adress of p1 is 2184620745864
The memory adress of p2 is 2184620746184
It seems really strange: The length of dictionary is 1. The memeory address of its key is the same as p1
. But I can access the dictionary via p2
.
If I delete the eq method, define only hash, like this:
class Position():
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return hash((self.x, self.y))
The length of dictionary d
will become 2
:
Hash values are equal: True
Length of d is 2
d[p1]=2
d[p2]=4
The memory adress of key is 2184620861960
The memory adress of key is 2184620862152
The memory adress of p1 is 2184620861960
The memory adress of p2 is 2184620862152
My question is: How Python compare the keys in dictionary to make them unique? Via hash value? via ==
? or via is
?
Thanks in avance for your discussions and answers!