简体   繁体   中英

Python: get item from set based on key

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 ? ie 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 don't need to use sets, you can get O(1) lookup using dict. Just use your key as the key for the dict items:

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

You can use dict comprehension to make it cleaner:

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

or in 2.6:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM