2

(sorry for vague title)

dic = {1:20, 2:20, 3:20, 4:10}

I want it to return 3, because that's the highest key number between the three duplicate values in the dictionary.

What I currently have is:

return max(dic, key = dic.get)

But this won't get my desired result and will return 1

0

2 Answers 2

6

Maximize over (value, key) pairs:

k, _ = max(dic.items(), key=lambda item: item[::-1])

dict items are tuples, and tuples are ordered lexicographically.

2
  • What does the k, _ and the lambda do? I'm sorry I'm new to python
    – Denferno
    May 12, 2021 at 23:43
  • The lambda reverses each item, with the effect that "highest value" takes precedence over "highest key" in each pair. The max returns a pair, but you only care about the first item in the pair here, so an assignment to _ indicates "throwing away" the other item.
    – wim
    May 12, 2021 at 23:57
1

Alternative to @wim's solution:

k, _ = sorted(dic.items(), key=lambda x: x[::-1])[-1]
5
  • 1
    Just to be clear sorted() needs to do quite a bit more work than max() right? Is there any reason to use this instead of max()?
    – Mark
    May 12, 2021 at 23:50
  • Slightly more, but I guess it depends on the implementation. max also needs to run through all elements in the collection and do comparison by key. @wim's answer is a no-brainer here, by all means.
    – VisioN
    May 12, 2021 at 23:53
  • 2
    Seems like it would be O(n) vs O(n log(n)).
    – Mark
    May 12, 2021 at 23:54
  • 1
    Yes, in the best case. There is no particular reason to use this solution, it was given purely for illustration.
    – VisioN
    May 12, 2021 at 23:59
  • 1
    The difference between sort and max is really small for most applications. If the difference really matters, perhaps you should consider other alternatives faster than Python.
    – C-3PO
    May 13, 2021 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.