views:

342

answers:

4

I'm just confused about why my code would not work, here's the question and the code I have so far (the test run says my answer is wrong).

Given the dictionary d, find the largest key in the dictionary and associate the corresponding value with the variable val_of_max. For example, given the dictionary {5:3, 4:1, 12:2}, 2 would be associated with val_of_max. Assume d is not empty.

d = {5:3, 4:1, 12:2, 14:9}
val_of_max = max(d.keys())
print val_of_max
+11  A: 

your code prints the key with the maximum value. What you want is:

d = {5:3, 4:1, 12:2, 14:9}
val_of_max = d[max(d.keys())]
print val_of_max

That is, you have to dereference the key to return the value.

Nathan Fellman
Hmm, so I just misread the question, that's good. Thanks so much. ^^
CP
this would be slightly more efficient if you used .iterkeys() rather than .keys()
ʞɔıu
@ʞɔıu: it would be more efficient if you get rid of any dict methods altogether.
SilentGhost
Oh, I'm not trying to write the most efficient code (though I would if I were more of an expert in Python). I'm just trying to fix the guy's code.
Nathan Fellman
+4  A: 

this will do:

>>> d = {5:3, 4:1, 12:2, 14:9}
>>> d[max(d)]
9
>>> max(d)        # just in case you're looking for this
14
SilentGhost
Actually I was trying to find the max key value not the max value.
CP
in your example maximum key corresponds to maximum value. I do exactly the same thing Nathan does, just in a sane and more efficient way.
SilentGhost
+1, there's absolutely no point in using max(d.keys()) when max(d) works just as well!
Alex Martelli
+1  A: 

Same code but remember to call the value of the key:

d = {5:3, 4:1, 12:2, 14:9}
val_of_max = max(d.keys())
print d[val_of_max]
mandel
A: 
d= {5:3, 4:1, 12:2, 14:9}

To print the value associated with the largest key:

print max(d.iteritems())[1]

To print the key associated with the largest value:

import operator
print max(d.iteritems(), key=operator.itemgetter(1))[0]
ΤΖΩΤΖΙΟΥ