[Python-Dev] Getting values stored inside sets

Terry Reedy tjreedy at udel.edu
Fri Apr 3 14:26:02 CEST 2009


Hrvoje Niksic wrote:
> I've stumbled upon an oddity using sets.  It's trivial to test if a 
> value is in the set, but it appears to be impossible to retrieve a 
> stored value, 

Set elements, by definition, do not have keys or position by which to 
grab.  When they do, use a dict or list.

> other than by iterating over the whole set.  Let me 
> describe a concrete use case.
> 
> Imagine a set of objects identified by some piece of information, such 
> as a "key" slot (guaranteed to be constant for any particular element). 
>  The object could look like this:
> 
> class Element(object):
>     def __init__(self, key):
>         self.key = key
>     def __eq__(self, other):
>         return self.key == other
>     def __hash__(self):
>         return hash(self.key)
>     # ...
> 
> Now imagine a set "s" of such objects.  I can add them to the set:
> 
>  >>> s = set()
>  >>> s.add(Element('foo'))
>  >>> s.add(Element('bar'))
> 
> I can test membership using the keys:
> 
>  >>> 'foo' in s
> True
>  >>> 'blah' in s
> False
> 
> But I can't seem to find a way to retrieve the element corresponding to 
> 'foo', at least not without iterating over the entire set.  Is this an 
> oversight or an intentional feature?  Or am I just missing an obvious 
> way to do this?

Use a dict, like you did.
> 
> I know I can work around this by changing the set of elements to a dict 
> that maps key -> element, but this feels unsatisfactory.

Sorry, that is the right way.

 >  It's
> redundant, as the element already contains all the necessary 
> information,

Records in a database have all the information of the record, but we 
still put out fields for indexes.

tjr



More information about the Python-Dev mailing list