Lets say I have a list:
JavaScript
x
2
1
t = [('a', 1), ('a', 6), ('b', 2), ('c', 3), ('c', 5), ('d', 4)]
2
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:
JavaScript
1
2
1
t = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
2
How can I achieve that?
Advertisement
Answer
You can use a dictionary to help you filter the duplicate keys:
JavaScript
1
12
12
1
>>> t = [('a', 1), ('a', 6), ('b', 2), ('c', 3), ('c', 5), ('d', 4)]
2
>>> d = {}
3
>>> for x, y in t:
4
if x not in d:
5
d[x] = y
6
7
>>> d
8
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
9
>>> t = list(d.items())
10
>>> t
11
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
12