Dictionary type access to list of instances

Brian Kelley bkelley at wi.mit.edu
Mon Feb 25 16:40:04 CET 2002


Grant Beasley wrote:

> Hi
> 
> If I have a list of instances, each with a property which I want to use as a
> key to access the list in dictionary-like manner, what would be the best way
> of doing this?
> 
> eg.
> func get(list, property, value):
>     for x in list:
>         if getattr(x, property) == value:
>             return x
> 

In this usage, getattr will raise an Attribute error if property doesn't 
exist which might not be what you want.

Here is an attempt using list comprehensions and the built-in list.index 
function.  I have created a NotEqual class so that getattr can return a 
default value is never equal to any other instance.  This is because 
None might be a valid value for a property.

class NotEqual:
     """instances of this class are never equal to anything"""
     def __eq__(self, other):
         return 0

def get(inputList, property, value, default=NotEqual()):
     try:
         properties = [getattr(x, property, default) for x in inputList]
         return inputList[properties.index(value)]
     except ValueError:
         raise ValueError, "attribute %s with value %s not found"%(
             `property`, `value`)

if __name__ == "__main__":
     class Foo:
         def __init__(self):
             self.dog = 1

     foo = Foo()
     print get([foo], 'dog', 1)
     try:
         get([foo], 'dog', 2)
     except ValueError, msg:
         print 'error caught:', msg

     try:
         get([foo], 'cat', 'raisin')
     except ValueError, msg:
         print 'error caught:', msg




More information about the Python-list mailing list