Skip to content Skip to sidebar Skip to footer

Check For Unique Values In A Dictionary And Return A List

I've been struggling with this exercise for a couple of days now, each approximation I find, have a new problem, the idea is to find those unique values on a dictionary, and return

Solution 1:

You just need to use your vals dict and keep keys from aDict with values that have a count == 1 in vals then calling sorted to get a sorted output list:

defexistsOnce3(aDict):  
    vals = {}
    # create dict to sum all value countsfor i in aDict.values():
        vals.setdefault(i,0)
        vals[i] += 1# use each v/val from aDict as the key to vals# keeping each k/key from aDict if the count is 1returnsorted(k for k, v in aDict.items() if vals[v] == 1)

Using a collections.Counter dict to do the counting just call Counter on your values then apply the same logic, just keep each k that has a v count == 1 from the Counter dict:

from collections import Counter
cn = Counter(aDict.values())
print(sorted(k for k,v in aDict.items() if cn[v] == 1))

Solution 2:

How about this:

fromcollectionsimportCountermy_dict= {1:1, 3:2, 6:0, 7:0, 8:4, 10:0}

val_counter=Counter(my_dict.itervalues())my_list= [kfork, vinmy_dict.iteritems()ifval_counter[v] ==1]

printmy_list

Result:

[1, 3, 8]

Solution 3:

One liner:

>>>aDictionary  = {1: 1, 3: 2, 6: 0, 7: 0, 8: 4, 10: 0}>>>unique_values = [k for k,v in aDictionary.items() iflist(aDictionary.values()).count(v)==1]>>>unique_values
[1, 3, 8]

Post a Comment for "Check For Unique Values In A Dictionary And Return A List"