开发者

Finding the highest key

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, 开发者_如何学C4: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


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.


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


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]


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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜