emu
emu

Reputation: 1673

Python: Access members of a set

Say I have a set myset of custom objects that may be equal although their references are different (a == b and a is not b). Now if I add(a) to the set, Python correctly assumes that a in myset and b in myset even though there is only len(myset) == 1 object in the set.

That is clear. But is it now possible to extract the value of a somehow out from the set, using b only? Suppose that the objects are mutable and I want to change them both, having forgotten the direct reference to a. Put differently, I am looking for the myset[b] operation, which would return exactly the member a of the set.

It seems to me that the type set cannot do this (faster than iterating through all its members). If so, is there at least an effective work-around?

Upvotes: 6

Views: 3350

Answers (3)

Mark Byers
Mark Byers

Reputation: 838226

I don't think that set supports retrieving an item in O(1) time, but you could use a dict instead.

d = {}
d[a] = a
retrieved_a = d[b]

Upvotes: 5

georg
georg

Reputation: 214969

Maybe this:

(myset - (myset - set([b]))).pop() is a

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122376

If you only have myset and b, then from that perspective, you won't have access to a because it's not there. If you create multiple mutable objects and add one of them to myset then the others are not 'known' when you're dealing with just myset or the object that you added.

If you want to modify a and b then you need to keep track of both objects somewhere.

Upvotes: 0

Related Questions