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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

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

2 Comments

That just gives me a de-duped list of objects, not the ids.
ah sorry, i misread. basically i would do what windwarrior does in his answer then...
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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.