Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove duplicate from list of tuple

How to remove duplicate from this tuple when the field#2 (f#2) are identical except for field1 (f#1)

#!/usr/bin/env python3
group = (#f#1        f#2
        (1658, 'alps no shoujo heidi'),
        (1659, 'alps no shoujo heidi'),
        (1660, 'alps no shoujo heidi'),
        (1661, 'alps no shoujo heidi'),
        (1662, 'alps no shoujo heidi'),
        (1663, 'alps no shoujo heidi'),
)

titles = list(dict.fromkeys(group))
print(titles)

I’m trying to get this output:

(1663, ‘alps no shoujo heidi’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

or

(1658, ‘alps no shoujo heidi’)

>Solution :

This is an approach where you can reduce the list by saving all Strings that have been encountered before:

already_found = []
reduced_group = []
for item in group:
    if item[1] not in already_found:
        already_found.append(item[1])
        reduced_group.append(item)


print(reduced_group)

This way you will always keep the first tuple that contains a duplicated String.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading