[Tutor] Return keys with unique values from a dict

Mats Wichmann mats at wichmann.us
Tue May 8 19:51:21 EDT 2018

On 05/08/2018 04:33 PM, Glen wrote:
> Hello,
> I had a task to define a function that would take a dict input and return
> only the keys with unique values into a list.
> Here is my code, which was awarded full marks, but I am pretty unhappy with
> it. I feel like I did a band-aid job after my first submission did pass
> mall the unit tests. I'd appreciate any advice on a better way to do this
> if anyone has some extra time.
> Thanks,
> def uniqueValues(theDict):
>     '''
>     theDict: a dictionary
>     '''
>     ans = []
>     rev = {}
>     toDel = []
>     for key, value in aDict.items():
>         if value not in rev:
>             rev[value] = key
>         elif value in rev:
>             toDel.append(value)
>     for item in toDel:
>         try:
>             del rev[item]
>         except:
>             pass
>     for item in rev:
>         ans.append(rev[item])
>     return sorted(ans)

There are many ways to tackle this - if you get six answers you'll
probably get six different ones :) You're already using the trick of
flipping, or reversing the dictionary, so we can maybe tweak that a
little bit - this is not the only way, you could use try/except instead
of get() to handle the case of the not-yet-added key:

for key, value in theDict.items():
    rev[value] = rev.get(value, [])

Having reversed the dict, you can build your answer list on the fly by
knowing that value lists (of keys from the original) which have a size
of 1 are "unique", if the (new) key has multiple values, then those were
not unique. You then pull out the value from that list and add it to
your answer list.

ans = [value[0] for key, value in rev.items() if len(value) == 1]

Whether that's "better" than your answer is up for discussion, but
something to think about.

The choice of answers may also depend a bit on the character of the data.

More information about the Tutor mailing list