In general, Python collections do not seem to be designed to extract items with a key. Obviously, what dictionaries are for. But is there anyway that, given the key, you can get an instance from the set that is equal to the key?
Again, I know that this is exactly what dictionaries are for, but as far as I can see, there are legitimate reasons to want to do this with a set. Suppose you have a specific class:
class Person: def __init__(self, firstname, lastname, age): self.firstname = firstname self.lastname = lastname self.age = age
Now suppose that I am going to create a large number of Person objects, and every time I create a Person object, I need to make sure that it is not a duplicate of the previous Person object. A Person is considered a duplicate of another Person if it has the same firstname , regardless of other instance variables. Thus, it is natural that you need to do everything to insert all Person objects into the set and define the __hash__ and __eq__ so that Person objects are compared by their firstname .
An alternative would be to create a dictionary of Person objects and use the first created firstname string as the key. The disadvantage here is that I will duplicate the firstname string. In most cases, this is not a problem, but what if I have 10,000,000 Person objects? The backup row storage can really be offset in terms of memory usage.
But if two Person objects are compared the same way, I need to get the source object so that additional instance variables (except firstname ) can be combined in the way that business logic requires. This brings me back to my problem: I need a way to retrieve instances from set .
Is there anyway to do this? Or uses the dictionary only as a real option?