set using alternative hash function?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Oct 15 17:15:42 CEST 2009


En Thu, 15 Oct 2009 11:42:20 -0300, Austin Bingham  
<austin.bingham at gmail.com> escribió:

> On Thu, Oct 15, 2009 at 4:06 PM, Anthony Tolle <anthony.tolle at gmail.com>  
> wrote:
>> Why not use a dict?  The key would be the object name.  Pretty much
>> the same behavior as a set (via the key), and you can still easily
>> iterate over the objects.
>
> To reiterate, dict only gets me part of what I want. Whereas a set
> with uniqueness defined over 'obj.name' would guarantee no name
> collisions, dict only sorta helps me keep things straight; it doesn't
> actually enforce that my values have unique names.

I think you didn't understand correctly Anthony Tolle's suggestion:

py> class Foo:
...   def __init__(self, name): self.name = name
...
py> objs = [Foo('Joe'), Foo('Jim'), Foo('Tom'), Foo('Jim')]
py> objs
[<__main__.Foo instance at 0x00BB8238>,
  <__main__.Foo instance at 0x00BB83C8>,
  <__main__.Foo instance at 0x00BB7B20>,
  <__main__.Foo instance at 0x00BB7DC8>]
py> d = dict((o.name, o) for o in objs)
py> d.keys()
['Jim', 'Joe', 'Tom']
py> d.values()
[<__main__.Foo instance at 0x00BB7DC8>,
  <__main__.Foo instance at 0x00BB8238>,
  <__main__.Foo instance at 0x00BB7B20>]

keys in a dict are unique; values form the set you're looking for. If it's  
more complex that just a name, define a function:

def my_funny_key_extractor(item):
   return some(operations[on](item))

d = dict((my_funny_key_extractor(o), o) for o in objs)

If you feel so inclined, you could implement the MutableSet ABC based on  
this and have a full featured set implementation.

-- 
Gabriel Genellina




More information about the Python-list mailing list