Skip to content Skip to sidebar Skip to footer

Removing Duplicate Items By Value Within A Dict

Need some help here as I've been scratching my head for the past hour on this problem: items = {1: {'title': u'testing123', 'description': u'testing456'}, 2: {'title': u'testing123

Solution 1:

You can create your own function. I am using Python 3, but I think that the only things that slightly change are the items function of the dict class and the way exceptions are handled (syntax).

defremove_by_value(d, value):
    key = 0for k, v in d.items():  # iteritems if v == value:
            key = k
            breaktry:
        del d[key] # in case the value is not in the dictionaryexcept KeyError: 
        print('value not in the dictionary')
    return d

d = {"12":12, "14":14, "28":28}

print(remove_by_value(d, 28))  # print

Solution 2:

Make another dictionary that has the values as keys, and check against that

vals_seen = {}
for key, valin itemscopy.iteritems():
    ifval['description'] in vals_seen:
        del items[key]
    else:
        vals_seen[val['description']] = 1

Solution 3:

So, for every element, you want to see if its value exists in others.

The problem your code has is that you are checking key 1 against itself. You can exclude this case directly in the if by adding and key1 != key2.

If you invert the dict on the value that should be unique (or values, using a tuple), then you'd get the same result.

Solution 4:

This is how I would do it:

def customCount(value, d):
    return len([key for key in d if d[key]==value])

RemovedDuplicateDict = {k:items[k] for k in items.keys() if customCount(items[k], items) < 2}

Post a Comment for "Removing Duplicate Items By Value Within A Dict"