[Tutor] Return keys with unique values from a dict

Glen glenuk at gmail.com
Tue May 8 18:33:55 EDT 2018


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)


<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
Virus-free.
www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>


More information about the Tutor mailing list