I have a list of objects, each having an id. This list can contain duplicates. How can I get a unique list of ids?
4 Answers
You can add the id's as keys to a dictionary and obtain back the keys of it:
d = {}
for item in items:
d[item.id] = item
print d.keys()
Now, d.values() contains the items which have the unified ids. As long as no two different items have the same id the above is lossless.
Contrasting with other solutions (at the time of writing) this also provides a good mapping between the id and the item with the specified id.
Comments
I think the canonical way is the following:
org_list = [1,2,2,4,1,5,3]
list(set(org_list))
it does re-sort the list, so if that's an issue you need another method. See also:
How do you remove duplicates from a list in whilst preserving order? http://www.peterbe.com/plog/uniqifiers-benchmark