Python: get an element from a key-based set

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 do a setusing objects of this class.

t0, t1, t2 = Test(0, 10), Test(1, 5), Test(2, 10)
s = set([t0, t1, t2])

Now, is there a way to find objects from susing key? that is, I want:

find_using_key(s, 1) # should return [t1]

I know that I can do this by sorting through the elements in the set, but I feel that there must be an O (1) method for this, since it keyeffectively determines the "position" in set.

+4
source share
2 answers

... because the key effectively defines the "position" in the set

This is not true. Two elements can coexist in a set with the same key:

>>> t0, t1 = Test(1,1), Test(1,2)
>>> len(set((t0,t1)))
2

. , -.

: set. insert find. . , . dict .

+8

, O(1) dict. dict:

d = {}
d[t0.key] = t0
d[t1.key] = t1
d[t2.key] = t2

dict, :

d = {t.key: t for t in [t0,t1,t2]}

2.6:

d = dict((t.key,t) for t in [t0,t1,t2])
+4

Source: https://habr.com/ru/post/1531626/


All Articles