I have a class with a custom hash method.
class Test(object):
def __init__(self, key, value):
self.key = key # key is unique
self.value = value
def __hash__(self):
# 'value' is unhashable, so return the hash of 'key'
return hash(self.key)
I make a set using objects of this class.
t0, t1, t2 = Test(0, 10), Test(1, 5), Test(2, 10)
s = set([t0, t1, t2])
Now, is there any way to find objects from s using key? i.e. I want to do:
find_using_key(s, 1) # should return [t1]
I know I can do this by iterating over the items in the set, but I feel like there should be an O(1) method to do this since key effectively determines the 'position' in the set.
... since key effectively determines the 'position' in the set
That's not really true. Two elements with the same key can coexist in the set:
>>> t0, t1 = Test(1,1), Test(1,2)
>>> len(set((t0,t1)))
2
The hash value does not define equality. That would also not be possible, because you can have hash collisions.
Now as for your question: Don't use a set. It is defined by an abstract interface with the operations insert and find. It does not provide the operation you want. Whether a potential underlying implementation could theoretically support the operation you want is not really relevant. Instead, use a dict, and associate the keys with the instances.
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