Search code examples
listpython-2.7dictionarytuplesdefaultdict

How to remove duplicate in a list of tuples


I have been trying around with defaultdict / dictionary set to remove the duplicate, however, I could not achieved desired output. I will demonstrate with more details below. I wish to remove duplicate in the list of tuple below:

List of tuples: [('Samsung', 'Handphone'), ('Samsung', 'Handphone),('Samsung','Tablet'),('Sony','Handphone')]

My desired output will be:

Output: {('Samsung','Handphone','Tablet'),('Sony','Handphone')}

I would like remove those duplicate values in the tuple and append "tablet" together with the "Samsung" in a tuple as it belongs to the same company. I have tried using defaultdict / dictionary. However I could not get it. How do i go about doing it? I would like to welcome any suggestions or ideas that you have. Thank you.


Solution

  • As @cco said, your desired output is not possible, if you want to do further analysis with your dictionary then having keys and values is the best idea,

    Try this,

    from collections import defaultdict
    a=[('Samsung', 'Handphone'), ('Samsung', 'Handphone'),('Samsung','Tablet'),('Sony','Handphone')]
    a=list(set(a))
    final={}
    dic=defaultdict(list)
    for k,v in a:
        dic[k].append(v)
    
    for l,m in dic.iteritems():
        final[l]=m
    print final
    

    Output:

    {'Sony': ['Handphone'], 'Samsung': ['Tablet', 'Handphone']}