nit
nit

Reputation: 25

Find unique of dictionary by values

I have a dictionary in python, eg:

Input =

{1:0, 2:0, 3:1, 4:1, 5:2, 6:3, 7:4, 8:4}

I want the output to contain only unique values with the order preserved.

Expected Output:

{1:0, 3:1, 5:2, 6:3, 7:4}

Is there a simple pythonic way to day except just looping over the data and removing the key-value pair whenever we find the same value in dict.

Thanks

Upvotes: 0

Views: 213

Answers (2)

Martol1ni
Martol1ni

Reputation: 4702

You could iterate over the sorted keys like this, throwing the ones that are duplicates

d = {1:0, 2:0, 3:1, 4:1, 5:2, 6:3, 7:4, 8:4}

new_d = {}
for key, value in sorted(d.items()):
    if value not in new_d.values():
        new_d[key] = value
print new_d

>> {1: 0, 3: 1, 5: 2, 6: 3, 7: 4}

Upvotes: 0

TerryA
TerryA

Reputation: 60024

Dictionaries don't have order in python, so you may want to consider using an OrderedDict

>>> from collections import OrderedDict
>>> d = OrderedDict({1:0, 2:0, 3:1, 4:1, 5:2, 6:3, 7:4, 8:4})
>>> d
OrderedDict([(1, 0), (2, 0), (3, 1), (4, 1), (5, 2), (6, 3), (7, 4), (8, 4)])
>>> new_d = OrderedDict()
>>> for i, j in d.iteritems():
...     if j in new_d.values(): continue
...     new_d[i] = j
... 
>>> new_d
OrderedDict([(1, 0), (3, 1), (5, 2), (6, 3), (7, 4)])
>>> dict(new_d)
{1: 0, 3: 1, 5: 2, 6: 3, 7: 4}

Upvotes: 1

Related Questions