bob_cobb
bob_cobb

Reputation: 2269

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', 'description': u'testing456'},
3: {'title': u'testing123', 'description': u'testing456'},
4: {'title': u'testing123', 'description': u'testing456'},
5: {'title': u'testing123', 'description': u'testing456'},
6: {'title': u'something', 'description': u'somethingelse'}}

itemscopy = items.copy()

for key1, val1 in itemscopy.iteritems():
    for key2, val2 in itemscopy.iteritems():
        if val1.get('description') == val2.get('description'):
            del items[key2]

I'm trying to remove duplicates from the items dict, such that the result excludes all duplicates, however, I'm removing them all entirely such that my final result is:

{6: {'title': u'something', 'description': u'somethingelse'}}

When it should be:

{1: {'title': u'testing123', 'description': u'testing456'}, 6: {'title': u'something', 'description': u'somethingelse'}}

Upvotes: 1

Views: 242

Answers (4)

nbro
nbro

Reputation: 15837

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).

def remove_by_value(d, value):
    key = 0
    for k, v in d.items():  # iteritems 
        if v == value:
            key = k
            break
    try:
        del d[key] # in case the value is not in the dictionary
    except KeyError: 
        print('value not in the dictionary')
    return d

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

print(remove_by_value(d, 28))  # print

Upvotes: 3

ashwinjv
ashwinjv

Reputation: 2967

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}

Upvotes: 0

Barmar
Barmar

Reputation: 780871

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

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

Upvotes: 2

Javier
Javier

Reputation: 2776

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.

Upvotes: 0

Related Questions