Python – remove non-unique elements between lists

  • A+
Category:Languages

I have a dictionary of lists of image ids that belong to a class of images such as dog and cat. Some of the images contain both dogs and cats in the image, and I want to remove those images.

Lets say I have

{'cat':[1,2,3], 'dog':[2,3,4]} 

we can see that the images with id 2 and 3 have both cats and dogs. I want to exclude these images to get the following:

[[1],[4]] 

I have tried this so far:

from collections import Counter img_ids = {'cat':[1,2,3], 'dog':[2,3,4]} flattened = [item for sublist in img_ids.values() for item in sublist] flattened_unique = [k for k, v in dict(Counter(flattened)).items() if v < 2] filtered_ids_dfs = [] for key, val in img_ids.items():   filtered = [x for x in val if x in flattened_unique]   filtered_ids_dfs.append(filtered) print(filtered_ids_dfs) 

Is there a better or more elegant solution to this? Also there may be an arbitrary number of classes, so our dictionary may have cat, dog, chicken etc.

 


You can use a list comprehension:

d = {'cat':[1,2,3], 'dog':[2,3,4]} n = [[c for c in b if not any(c in h for j, h in d.items() if j != a)] for a, b in d.items()] 

Output:

[[1], [4]] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: