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

Remove duplicate from dictionary in python

I have 5 lists in a dictionary I want to delete duplicates and retain the element that occurs in first list by comparing all lists available

dict = {1:[0,1,2,3], 2:[1,4,5], 3:[0,4,2,5,6], 4:[0,2,7,8], 5:[9]}

Output should look like this:

dict = {1:[0,1,2,3], 2:[4,5], 3:[6], 4:[7,8], 5:[9]}

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

>Solution :

You can make a set to store items that have been seen, and then sequentially update the dict according to the set:

d = {1:[0,1,2,3], 2:[1,4,5], 3:[0,4,2,5,6], 4:[0,2,7,8], 5:[9]}

seen = set()
for k, v in d.items():
    d[k] = [x for x in v if x not in seen]
    seen.update(d[k])

print(d) # {1: [0, 1, 2, 3], 2: [4, 5], 3: [6], 4: [7, 8], 5: [9]}
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