Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - reporting key with highest value, or tie

Tags:

python

I know this is really simple, and it's probably already been answered somewhere, but I'm having lots of trouble finding it anywhere, probably because I'm searching for the wrong term.

I have something like this (but far more complicated):

score = {}
z = 4
while z > 0:
    score[z] = random.randrange(1,12)
    z -= 1

So eventually I arrive at these values:

score[1] = 7
score[2] = 9
score[3] = 12
score[4] = 7

I want something to set a variable to 3, because score[3] is the largest.

score[1] = 9
score[2] = 9
score[3] = 7
score[4] = 8

And in this instance, it should set the variable to 0 or something, because the highest number is a tie.

like image 297
user3750369 Avatar asked May 28 '26 21:05

user3750369


1 Answers

max_score = max(score.values())
keys = [k for k in score if score[k] == max_score]

This produces a list of the keys that have the highest score, whether that's one or more.

like image 163
Mark Ransom Avatar answered May 31 '26 10:05

Mark Ransom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!