Search code examples
pythondictionarykeykey-valuedefaultdict

Remove duplicates from dict values in python


I have a defaultdict of list like this

{'A':[1,2,3,3,2],'B':[1,2,3,3,2]}

Need to remove duplicates in the values only. The dict should be like

{'A':[1,2,3],'B':[1,2,3]}

Tried

dict((k, tuple(v)) for k, v in list_of_value.items())

Not helping much.


Solution

  • Just change the tuple to Set. As the property of set is to make it unique. The change it back to list.

    list_of_value = {'A':[1,2,3,3,2],'B':[1,2,3,3,2]}
    dict((k, list(set(v))) for k, v in list_of_value.items())