Search code examples
pythonlistdictionaryduplicatesdefaultdict

How to remove the duplicates values from only one element of the dictionary at a time?


In this given dictionary defaultdict(dict) type data:

{726: {'X': [3.5, 3.5, 2.0}, 'Y': [2.0, 0.0, 0.0], 'chr': [2, 2, 2]}, 128: {'X': [0.5, 4.0, 4.0], 'Y': [4.0, 3.5, 3.5], 'chr': [3, 3, 3]}}

the numeric value 726 and 128 are the keys and are unique. The other elements are the values tagged with unique identifier and are also unique.

I want to remove the duplicates only from the list values in chr without affecting the data or order of the values in any other parts of the dictionary.

How may I accomplish that?

Thanks,


Solution

  • If d is your dictionary, you can simply do :

    for k in d: d[k]['chr']=d[k]['chr'][0]
    

    assuming unique value in chr.

    If multiple values exists,

    for k in d: 
     l=d[k]['chr']+[None]
     d[k]['chr']=[x for (i,x) in enumerate(l[:-1]) if l[i]!=l[i+1]] 
    

    will make the job.