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
It doesn’t look like the keys are relevant at all. Therefore, you can just call
sorted:Your code
fails because iterating over a dictionary will yield its keys. Therefore, you are essentially calling
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 dictionaryitemsor retrieve the value in the lambda function (or viadict.get):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).