0

I need to create a function that removes keys if their values are duplicates in a dictionary. For example...

remove_dups({1:4, 2:4, 3:2})
{3:2}
remove dups({1:2, 2:5})
{1:2, 2:5}

I have no idea how to do this and where to start, please help! Need to know how to do this without list comprehensions or importing.

  • 1
    Could perhaps be of help: http://stackoverflow.com/questions/14766904/python-remove-duplicate-value-in-a-combined-dictionarys-list – Henrik Andersson Dec 10 '13 at 06:05
  • possible duplicate of [Python: Sort a dictionary by value](http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) – tiago Dec 10 '13 at 10:45

2 Answers2

1
def remove_dups(d):
    c, result = {}, {}
    for item in d.values():
        c[item] = c.get(item, 0) + 1
    for k, v in d.items():
        if c[v] == 1:
            result[k] = v
    return result

The best and simpler way to do this would be to use Counter and dict comprehension like this

from collections import Counter
def remove_dups(d):
    c = Counter(d.values())
    return {k:v for k, v in d.items() if c[v] == 1}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

Dictionaries has a function - dict.values() - getting all the values as a list

{1:4, 2:4, 3:2}.values() = [4,4,2]

Then you can user counter (from collection import Counter) - check the values with count greater than 1 and remove the keys which are associated with does values.

(I don't give the complete code since it sounds like a homework assignment)

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Tom Ron
  • 5,906
  • 3
  • 22
  • 38
  • It isn't a homework assignment. I'm studying for my final exams looking at my previous exams and I got stuck on this question, I'm just trying to learn as much as possible. – user3014764 Dec 10 '13 at 06:09
  • No problem - continuing the solution above - def remove_dups(d): c = Counter(d.values()) keys_to_remove = [] for k,v in d.iteritems(): if c[v]>1: keys_to_remove.append(k) for k in keys_to_remove: del(dict[k]) – Tom Ron Dec 10 '13 at 06:10