Dictionary type access to list of instances

Grant Beasley gbeasley at tsa.ac.za
Mon Feb 25 07:59:28 EST 2002


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

OR

func get(list, property, value):
    return filter(lambda x: getattr(x, property) == value, list)[0]

Note: Normally property would be fixed, and I probably don't need it as
flexible as this. i.e. get(list, value) would probably satisfy my needs.

I could do it using functions, or even overriding the UserDict class, but
ultimately I'll use a similar algorithm. Any comments or ideas appreciated.

Thanks
Grant Beasley





More information about the Python-list mailing list