0

so I have a dictionary which looks like this:

foo_dict = {'A' : 0.03, 'B' : 0.13, 'C' : 0.42, 'D' : 0.42}

And I got the maximum value with this line :

max_value = max(foo_dict.values())

As you see, the maximum value is 0.42 and there are two keys with that value-C and D. Now I want to get both C and D in a list. I've tried

max_key = max(foo_dict.keys(), key=lambda k : foo_dict[k])

But it only gives C. How do I get both(all) keys that have the same value that is max_value?
Thanks.

Ryan Oh
  • 597
  • 5
  • 21

1 Answers1

1

You can do this,

max_value = max(foo_dict.values())
[k for k,v in foo_dict.items() if v == max_value] # ['C', 'D']

max function can only return one value at a time. So you can find the max value using the first line, store the value and later loop over the dict and pick up the keys where value match with the max value.

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – ppwater Jan 15 '21 at 08:56