Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 435
emu Avatar asked Jun 17 '12 14:06

emu


1 Answers

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]
like image 173
Mark Byers Avatar answered Oct 03 '22 18:10

Mark Byers