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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With