0

I use a dictionary that looks somewhat like this:

data = {1: [3, 5], 2: [1, 2], 3: [1, 2, 3, 4], 4: [1, 2, 3], 5: [1, 2, 3]}

I want to delete values and their corresponding keys in that dictionary that are having exactly the same value. So my dictionary should look like this:

data = {1: [3, 5], 2: [1, 2], 3: [1, 2, 3, 4]}

I've tried to use this right here: Removing Duplicates From Dictionary But although I tried changing it, it gets quite complicated really fast and there is probably an easier way to do this. I've also tried using count() function, but it did not work. Here is what it looks like. Maybe I declared it the wrong way?

no_duplicates = [value for value in data.values() if data.count(value) == 1]

Is there an easy way the remove all key-value-pairs that are not unique with respect to their values?

cybel
  • 381
  • 2
  • 6
  • 16

1 Answers1

1

You can do this with a dictionary comprehension, where you make a dictionary with the key value pairs where the value count is 1

def get_unique_dict(data):

    #Get the list of dictionary values
    values = list(data.values())

    #Make a new dictionary with key-value pairs where value occurs exactly once
    return {key: value for key, value in data.items() if values.count(value) == 1}

data = {1: [3, 5], 2: [1, 2], 3: [1, 2, 3, 4], 4: [1, 2, 3], 5: [1, 2, 3]}

print(get_unique_dict(data))

The output will be

{
    1: [3, 5], 
    2: [1, 2], 
    3: [1, 2, 3, 4]
}
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40