Can't get items out of a set?

Alan Isaac aisaac at american.edu
Sat Mar 8 10:32:18 EST 2008


Cruxic wrote:

> people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )

> ... 

> p = people.get_equivalent(2)  #method doesn't exist as far as I know 

> print p.name  #prints Sue 



def get_equivalent(test, container):

  for p in container:

    if p == test:

      return p



hth,

Alan Isaac





#example (note change in __eq__ to match your case; fix if nec)



class Person:

  def __init__(self, id, name):

    self.id = id

    self.name = name

  def __hash__(self):

    return self.id

  def __eq__(self, other):

    return self.id == other



people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )



get_equivalent(2,people)



More information about the Python-list mailing list