3

I have a list of objects, each having an id. This list can contain duplicates. How can I get a unique list of ids?

Mark Richman
  • 28,948
  • 25
  • 99
  • 159

4 Answers4

4

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.

Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109
2

assuming that you want a list of all id's but without doubles

all_ids = [x.getId() for x in items]
no_double_ids = list(set(all_ids))
windwarrior
  • 456
  • 2
  • 11
0

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

Community
  • 1
  • 1
Carst
  • 1,614
  • 3
  • 17
  • 28
0
>>> class ObjectIdHolder(object):
...     def __init__(self, object_id):
...         self.object_id = object_id
... 
>>> ids = list(range(10)) * 2
>>> a = [ObjectIdHolder(x) for x in ids]
>>> unique_ids = {obj.object_id for obj in a}
>>> print unique_ids
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
hughdbrown
  • 47,733
  • 20
  • 85
  • 108