-2

I have a python dictionary that has objects as keys. The objects have certain attributes say:

class Ex: text count id

How do I enable constant time searching for an object with value equal to some text 'xyz'

Ex obj1 Ex obj2 Ex obj3 map = {obj1 : 1, obj2 : 2, obj3 : 3}

I want to know whether the 'has_key' or 'in' method of Python dictionary can achieve fetching objects with a particular attribute in constant time,i.e.,

map.has_key('xyz') will return me the presence of the corresponding object with text attribute as 'xyz' in constant time.

1 Answers1

0

You need to implement a __hash__ function for that class as well as a __eq__ method.

class Foo:
    def __init__(self, bar, bazz):
        self.bar = bar
        self.bazz = bazz

    def __hash__(self):
        return hash((self.bar, self.bazz))

    def __eq__(self, other):
        return (self.bar, self.bazz) == (other.bar, other.bazz)

That is assuming you want it to work such that Foo(5, 'a') == Foo(5, 'a'). But if you care solely about identity of objects (foo is bar) then you don't need to do anything at all, it will be O(1) already.

semicolon
  • 2,530
  • 27
  • 37