I have a list of tuples:
JavaScript
x
4
1
exampleList = [("a", "januari", 10), ("b", "februari", 12), ("a", "februari", 12)]
2
3
wantedList = [("a", "januari", 10), ("b", "februari", 12)]
4
So when the first item of the tuples in the list is double or more, i want to remove the duplicates. The end result has to be the wantedList. In a normal list i can do the “make a dictionary” trick but i dont know how to solve it with a list of tuples.
Advertisement
Answer
You can proceed with dict comprehension :
JavaScript
1
5
1
tmp_list = [("a", "januari", 10), ("b", "februari", 12), ("a", "februari", 12)]
2
tmp_dict = {elem[0]: elem for elem in tmp_list}
3
4
wanted_list = list(tmp_dict.values())
5
result is :
JavaScript
1
2
1
[('a', 'februari', 12), ('b', 'februari', 12)]
2
If you want to keep the first occurence, you can use reversed
:
JavaScript
1
5
1
tmp_list = [("a", "januari", 10), ("b", "februari", 12), ("a", "februari", 12)]
2
tmp_dict = {elem[0]: elem for elem in reversed(tmp_list)}
3
4
wanted_list = list(tmp_dict.values())
5
Which gives you :
JavaScript
1
2
1
[('a', 'januari', 10), ('b', 'februari', 12)]
2