Python data structure for a collection of objects with random access based on an attribute

后端 未结 4 1762
臣服心动
臣服心动 2021-02-06 15:31

I need a collection of objects which can be looked up by a certain (unique) attribute common to each of the objects. Right now I am using a dicitionary assigning the dictionary

4条回答
  •  星月不相逢
    2021-02-06 15:51

    Editing to correct the problem I had - which was due to my "collection = dict()" default parameter (*bonk*). Now, each call to the function will return a class with its own collection as intended - this for convenience in case more than one such collection should be needed. Also am putting the collection in the class and just returning the class instead of the two separately in a tuple as before. (Leaving the default container here as dict(), but that could be changed to Alex's WeakValueDictionary, which is of course very cool.)

    def make_item_collection(container = None):
        ''' Create a class designed to be collected in a specific collection. '''
        container = dict() if container is None else container
        class CollectedItem(object):
            collection = container
            def __init__(self, key, title=None):
                self.key = key
                CollectedItem.collection[key] = self
                self.title = title
            def update_key(self, new_key):
                CollectedItem.collection[
                    new_key] = CollectedItem.collection.pop(self.key)
                self.key = new_key
        return CollectedItem
    
    # Usage Demo...
    
    Item = make_item_collection()
    my_collection = Item.collection
    
    item_instance_1 = Item("unique_key1", title="foo1")
    item_instance_2 = Item("unique_key2", title="foo2")
    item_instance_3 = Item("unique_key3", title="foo3")
    
    for k,v in my_collection.iteritems():
        print k, v.title
    
    item_instance_1.update_key("new_unique_key")
    
    print '****'
    for k,v in my_collection.iteritems():
        print k, v.title
    

    And here's the output in Python 2.5.2:

    unique_key1 foo1
    unique_key2 foo2
    unique_key3 foo3
    ****
    new_unique_key foo1
    unique_key2 foo2
    unique_key3 foo3
    

提交回复
热议问题