Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: finding keys with unique values in a dictionary?

I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.

I will clarify with an example. Say my input is dictionary a, constructed as follows:

a = dict()
a['cat'] =      1
a['fish'] =     1
a['dog'] =      2  # <-- unique
a['bat'] =      3
a['aardvark'] = 3
a['snake'] =    4  # <-- unique
a['wallaby'] =  5
a['badger'] =   5  

The result I expect is ['dog', 'snake'].

There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.

like image 233
Roee Adler Avatar asked Jun 23 '09 12:06

Roee Adler


People also ask

How do you find the number of unique keys in a dictionary?

Use the len() Function to Count the Number of Keys in a Python Dictionary. The len() function in Python is used to return the total number of items present in an object. We can use the keys() method of the dictionary to get a list of all the keys in the dictionary and count the total number using len() .

Are Keys unique in dictionary Python?

Keys are not unique for a python dictionary!


2 Answers

I think efficient way if dict is too large would be

countMap = {}
for v in a.itervalues():
    countMap[v] = countMap.get(v,0) + 1
uni = [ k for k, v in a.iteritems() if countMap[v] == 1]
like image 80
Anurag Uniyal Avatar answered Sep 30 '22 15:09

Anurag Uniyal


Here is a solution that only requires traversing the dict once:

def unique_values(d):
    seen = {} # dict (value, key)
    result = set() # keys with unique values
    for k,v in d.iteritems():
        if v in seen:
            result.discard(seen[v])
        else:
            seen[v] = k
            result.add(k)
    return list(result)
like image 5
Rick Copeland Avatar answered Sep 30 '22 15:09

Rick Copeland