2
\$\begingroup\$

I'm working on this code for exam in an MIT Python course. It's working but I'm trying to improve it. What could I do, and what should I avoid?

aDict = {   0: 1, 
     1: 2, 
     2: 2, 
     4: 2, 
     5: 2,
            6: 3,
     7: 2}


values=list(aDict.values())
keys=list(aDict.keys())
value_copy=values[:]
uniqe=[]


m=0

for value in value_copy:
    m+=1
    if value in value_copy[m:]:
        while(values.count(value)):
            try:
                values.remove(value)
            except:
                pass

for val in values:
    uniqe.append(keys[value_copy.index(val)])

uniqe.sort()

print (uniqe)
\$\endgroup\$

migrated from stackoverflow.com Aug 10 '15 at 20:48

This question came from our site for professional and enthusiast programmers.

  • \$\begingroup\$ If you're trying to look up keys based on dictionary values, your dictionary might be backwards. \$\endgroup\$ – TigerhawkT3 Aug 10 '15 at 20:44
  • \$\begingroup\$ Your indentation of aDict is ugly, make it pretty. Never use a catch-all except block. Don't use variable names similar to function names or keywords. \$\endgroup\$ – machine yearning Aug 10 '15 at 20:47
4
\$\begingroup\$

A more efficient way (in terms of lines of code) of doing the same thing would be to use this code. The code declares a new dictionary countMap and then loops over the items in aDict. The first loop increases the entry in countMap that corresponds to the current value of aDict which is being evaluated and then increases the value in countMap if it's already been found but if it hasn't then it sets the corresponding value in countMap to 0 and then increments the value (initially setting every value to 1 or if it's already been found then incrementing it). The second loop only adds values within countMap to the list uni if there values equal 1 (if the current entry is unique).

Taken from here:

aDict = {
        0: 1, 
        1: 2, 
        2: 2, 
        4: 2, 
        5: 2,
        6: 3,
        7: 2}

countMap = {}
for v in aDict.values():
    countMap[v] = countMap.get(v,0) + 1
uni = [ k for k, v in aDict.items() if countMap[v] == 1]    
print(uni)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy