Skip to content
Advertisement

Remove elements from tuple array that have same value in first index position of each element

Lets say I have a list:

t = [('a', 1), ('a', 6), ('b', 2), ('c', 3),  ('c', 5), ('d', 4)]

There are two tuples with ‘a’ as the first element, and two tuples with ‘c’ as the first element. I want to only keep the first instance of each, so I end up with:

t = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

How can I achieve that?

Advertisement

Answer

You can use a dictionary to help you filter the duplicate keys:

>>> t = [('a', 1), ('a', 6), ('b', 2), ('c', 3),  ('c', 5), ('d', 4)]
>>> d = {}
>>> for x, y in t:
...     if x not in d:
...             d[x] = y
...
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> t = list(d.items())
>>> t
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement