Dennis Dennis - 3 months ago 7
Python Question

Return list element by the value of one of its attributes

There is a list of objects

l = [obj1, obj2, obj3]


Each
obj
is an object of a class and has an
id
attribute.

How can I return an
obj
from the list by its
id
?

P.S.
id
s are unique. and it is guaranteed that the list contains an object with the requested
id

Answer

Assuming the id is a hashable object, like a string, you should be using a dictionary, not a list.

l = [obj1, obj2, obj3]
d = {o.id:o for o in l}

You can then retrieve objects with their keys, e.g. d['ID_39A'].