# Unique dictionary values - print keys

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)

• If you're trying to look up keys based on dictionary values, your dictionary might be backwards. – TigerhawkT3 Aug 10 '15 at 20:44
• 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. – machine yearning Aug 10 '15 at 20:47

## 1 Answer

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)