Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: get item from set based on key

Tags:

python

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.

like image 630
Jayanth Koushik Avatar asked Jun 30 '26 15:06

Jayanth Koushik


1 Answers

... 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.

like image 91
Niklas B. Avatar answered Jul 03 '26 05:07

Niklas B.