Alejandro
Alejandro

Reputation: 5236

second maximum value in dictionary python

I have a regular dictionary like:

A = {37:4783, 92:47834, 12:234234,....}

I need to return the second maximum value, the third, and so on. I was trying with:

max(A, key=lambda x: x[1])

but I got this error: TypeError: 'float' object is unsubscriptable

what am I doing wrong?

thanks

Upvotes: 1

Views: 6739

Answers (1)

phihag
phihag

Reputation: 288270

It doesn't look like the keys are relevant at all. Therefore, you can just call sorted:

>>> A = {37:4783, 92:47834, 12:234234}
>>> sorted(A.values(), reverse=True)
[234234, 47834, 4783]

Your code

max(A, key=lambda x: x[1])

fails because iterating over a dictionary will yield its keys. Therefore, you are essentially calling

max([37, 92, 12], key=lambda x:x[1])

As you can see, the key doesn't make any sense here; 37[1] will throw an error. If you want to sort the keys by the corresponding values, either sort the dictionary items or retrieve the value in the lambda function (or via dict.get):

>>> [k for k,v in sorted(A.items(), key=lambda item: item[1], reverse=True)]
[12, 37, 92]
>>> sorted(A, key=lambda k: A[k], reverse=True)
[12, 37, 92]
>>> sorted(A, key=A.get, reverse=True)
[12, 37, 92]

Note that the latter may be slower since you need to retrieve every key from the dictionary (although dictionary access is really fast in Python).

Upvotes: 7

Related Questions