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

后端 未结 4 1756
臣服心动
臣服心动 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:59

    Well, dict really is what you want. What may be cumbersome is not the dict itself, but the way you are building it. Here is a slight enhancement to your example, showing how to use a list expression and the dict constructor to easily create your lookup dict. This also shows how to create a multimap kind of dict, to look up matching items given a field value that might be duplicated across items:

    class Item(object):
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)
        def __str__(self):
            return str(self.__dict__)
        def __repr__(self):
            return str(self)
    
    allitems = [
        Item(key="red", title="foo"),
        Item(key="green", title="foo"),
        Item(key="blue", title="foofoo"),
        ]
    
    # if fields are unique
    itemByKey = dict([(i.key,i) for i in allitems])
    
    # if field value can be duplicated across items
    # (for Python 2.5 and higher, you could use a defaultdict from 
    # the collections module)
    itemsByTitle = {}
    for i in allitems:
        if i.title in itemsByTitle:
            itemsByTitle[i.title].append(i)
        else:
            itemsByTitle[i.title] = [i]
    
    
    
    print itemByKey["red"]
    print itemsByTitle["foo"]
    

    Prints:

    {'key': 'red', 'title': 'foo'}
    [{'key': 'red', 'title': 'foo'}, {'key': 'green', 'title': 'foo'}]
    

提交回复
热议问题