Background
I have a list.
This list has many objects. Each object has an id. Now the objects are of different types.
objects = [Aobject, Bobject, Cobject]
where
>>> Aobject != Bobject
True
>>> Aobject.id == Bobject.id
True
Problem
I want a list of unique objects based on the object.id.
Something like this:
set(objects, key=operator.attrgetter('id'))
(This does not work. But I want something like this)
You can use a
set:Or equivalently:
This works because
set.addreturnsNone, so the expression in the list comprehension always yieldsobj, but only ifobj.idhas not already been added toseen.The expression could only evaluate to
Noneifobj is None; in that case,obj.idwould raise an exception. In casemylistcontainsNonevalues, change the test toif obj and (obj.id not in seen).Note that for each
obj.id, this will keep the firstobjin the list which has thatobj.id.Update
Alternatively, you can use a
dict:Note that for each
obj.id, this will keep the firstobjin the list which has thatobj.id. Remove the test if you want to keep the last suchobj, or use @Abhijit’s answer.