1

In a dict, I want to find all keys that have the highest value, so in this example not only key 'D', but also key 'B'. How do I do this (in the most efficient way)?

some_dict = {
'A': 2, 
'B': 18, 
'C': 7, 
'D': 18
}

highest_keys(some_dict)

# Result should be: ['B', 'D'] or {'B': 18, 'D': 18}, both options would work

max only gives the last key with the highest value, but I need all. Thank you in advance! :)

Max
  • 99
  • 6
  • 2
    FYI: `max(some_dict)` gives `D` because "D" is the highest letter in lexicographical order. It doesn't look at the numbers at all. If it did look at the numbers, you'd expect `C` to be the answer… – deceze Mar 24 '22 at 12:03
  • What deceze said. Highest int would be 17, so key "C". | As to hints: The easiest here would be to "invert" the dictionary into number -> list of keys. So when you get your value you want (through max on values/this new dict, or what you had so far) you will get all letter associated with it – h4z3 Mar 24 '22 at 12:05
  • I saw I put the values wrong in the example, sorry! 'B' and 'D' now both have the highest val – Max Mar 24 '22 at 12:09

3 Answers3

3

You may find the highest value, and then retrieve the keys:

highval = max(somedict.values())
[k for k in somedict if somedict[k] == highval]
gimix
  • 3,431
  • 2
  • 5
  • 21
0

This should work

sorted_keys = sorted(some_dict,key=lambda x:some_dict[x], reverse=True)
highest_value = some_dict[sorted_keys[0]]
for key in sorted_keys:
    value = some_dict[key]
    if value != highest_value:
        break
    else:
        print(key)
Underoos
  • 4,708
  • 8
  • 42
  • 85
-1
some_dict = {
'A': 2, 
'B': 8, 
'C': 17, 
'D': 8
}
print(dict(max(some_dict.items(), key=lambda x: x[1])))

this key is checking the max value, and then converting it back to dict

Ryuga
  • 132
  • 1
  • 1
  • 8