Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a dictionary value by custom object value in Python?

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

like image 453
Sam Avatar asked Apr 09 '10 03:04

Sam


People also ask

Can an object be a value in a dictionary Python?

Takeaway: A dictionary key must be an immutable object. A dictionary value can be any object.

Can you use an object as a key in a Python dictionary?

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.


2 Answers

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.

like image 115
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 06:09

Ignacio Vazquez-Abrams


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.
like image 24
David Avatar answered Sep 28 '22 05:09

David