So I have a square that's made up of a series of points. At every point there is a corresponding value.
What I want to do is build a dictionary like this:
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
square = {}
for x in range(0, 5):
for y in range(0, 5):
point = Point(x,y)
square[point] = None
However, if I later create a new point object and try to access the value of the dictionary with the key of that point it doesn't work..
>> square[Point(2,2)]
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
square[Point(2,2)]
KeyError: <__main__.Point instance at 0x02E6C378>
I'm guessing that this is because python doesn't consider two objects with the same properties to be the same object? Is there any way around this? Thanks
Takeaway: A dictionary key must be an immutable object. A dictionary value can be any object.
Almost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions.
Define Point.__hash__()
and Point.__eq__()
so that they can be compared properly within dicts.
And while you're at it, consider defining Point.__repr__()
so that you get decent-looking representations of your Point
objects.
Yes, define the __eq__
and __hash__
methods on your Point class.
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def __eq__(self, other):
return self._x == other._x and self._y == other._y
def __hash__(self):
#This one's up to you, but it should be unique. Something like x*1000000 + y.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With