How to get list of objects with unique attribute
list, python, set
Solution
You can use a `set`:
seen = set()
uniqueidlist = []
for obj in mylist:
if obj.id not in seen:
seen.add(obj.id)
uniqueidlist.append(obj)
Or equivalently:
seen = set()
uniqueidlist = [seen.add(obj.id) or obj for obj in mylist if obj.id not in seen]
This works because `set.add` returns `None`, so the expression in the list comprehension always yields `obj`, but only if `obj.id` has not already been added to `seen`.
The expression could only evaluate to `None` if `obj is None`; in that case, `obj.id` would raise an exception. In case `mylist` contains `None` values, change the test to `if obj and (obj.id not in seen)`.
Note that for each `obj.id`, this will keep the first `obj` in the list which has that `obj.id`.
Update
Alternatively, you can use a `dict`:
seen = {}
for obj in mylist:
if obj.id not in seen:
seen[obj.id] = obj
uniqueidlist = list(seen.values())
Note that for each `obj.id`, this will keep the first `obj` in the list which has that `obj.id`. Remove the test if you want to keep the last such `obj`, or use @Abhijit’s answer.
Problem
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)