Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicated tuples from list based on the first entry of tuple [duplicate]

I have a list of tuples like this one here:

test = [('ent1', 24), ('ent2',12), ('ent3',4.5), ('ent1', 4), ('ent2', 3.5)]

I would like to remove those tuples from the list where the first element has already appeared. So the desired output would be

[('ent1', 24), ('ent2',12), ('ent3',4.5)]

I have no idea how to do this. Normally, if I would like to remove exact duplicated tuples, I would use

list(set(test))

but this is not working in this case. Has anybody an appropriate approach for this problem?

like image 545
WinterMensch Avatar asked Jan 03 '23 01:01

WinterMensch


1 Answers

How do you like the output of dict(test)?

{'ent1': 4, 'ent2': 3.5, 'ent3': 4.5}

Or you may want to convert this back to a list of tuples with

>>> list(dict(test).items())
[('ent1', 4), ('ent2', 3.5), ('ent3', 4.5)]

Edit: This will keep the last assigned value but you can also keep the first assigned value by reversing first your list:

>>> list(dict(reversed(test)).items())
[('ent2', 12), ('ent1', 24), ('ent3', 4.5)]

Edit2: If you want to preserve list order, as well, this seems to be a good one-liner solution (inspired by Julien's answer):

>>> [(uk,next(v for k,v in test if k == uk)) for uk in dict(test).keys()]
[('ent1', 24), ('ent2', 12), ('ent3', 4.5)]

And finally, you with functools.reduce you can get another one-liner:

>>> from functools import reduce
>>> reduce(lambda lu,i:i[0] in dict(lu).keys() and lu or lu+[i], test, [])
[('ent1', 24), ('ent2', 12), ('ent3', 4.5)]

Explanation: lu is the list with only unique keys, i is the next item from the test list. If i[0], i.e. the key of the next element is in lu already, we keep lu, otherwise we append i.

like image 101
tif Avatar answered Jan 05 '23 17:01

tif