Accessing a dictionary value by custom object value in Python?

Posted by Sam on Stack Overflow See other posts from Stack Overflow or by Sam
Published on 2010-04-09T03:12:12Z Indexed on 2010/04/09 3:13 UTC
Read the original article Hit count: 329

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about python

Related posts about dictionary