-2

How do I find the dictionary key for the value that maximizes some attribute or function func(value) w/o explicit looping? For example, the longest string (when func==len):

d = {'x':'foo', 'a':'string', 'b':'house', 'c':'bar'}
longest = ??  # should return 'a' in this example

There is a related question asking about the maximum value, corresponding to the identity function, but it's not clear to me how to adapt the answers to that post to my use case here.

Walter
  • 44,150
  • 20
  • 113
  • 196
  • 2
    Without looping, you can't. It's O(n) because you have to see all of the values to decide which is longest. – jonrsharpe Mar 10 '21 at 14:10
  • 1
    I downvoted, its unclear what you're asking and it doesn't show any attempt at solving or researching this problem yourself. – Sayse Mar 10 '21 at 14:12
  • @Sayse I cannot understand how it's unclear what I'm asking. It's true, though, that my attempts to find a solution are not evident in the post. I wanted to make it short. – Walter Mar 10 '21 at 14:15
  • Because "that maximizes some attribute or function" is very vague, sure the answer below gives you the key for the value with the longest string but that would have been described easier by find the key whose value is the longest string. Thus it would lead me to believe that this example is simplified too much for the actual use case – Sayse Mar 10 '21 at 14:22
  • The basic approaches are well covered in e.g. https://stackoverflow.com/q/268272/3001761. – jonrsharpe Mar 10 '21 at 14:29
  • @jonrsharpe Yes, I have seen that question, but it was concerned with the *maximum value*, while I need the *value that maximizes some attribute*. Essentially, I could have asked how to adapt the answers to that question to my problem. – Walter Mar 11 '21 at 09:16
  • @Sayse I still don't understand what's unclear about *maximizes some attribute or function*. `len` is just an example. If it works for `len`, it will work for any other attribute or function. The general advice is to produce a [MVCE](https://stackoverflow.com/help/minimal-reproducible-example), not the full use case. IMHO your downvote is unjustified and contra-productive. Regards to Derby (I lived many years in UK, 15 of which in Leicester). – Walter Mar 11 '21 at 09:25

1 Answers1

1

you can use max

dict_ = {'a':'string','b':'house','c':'bar'}

max((len(v), k) for k,v in dict_.items())[-1]
'a'
Epsi95
  • 8,832
  • 1
  • 16
  • 34