Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Max Key in dictionary in case of tie

I have a dictionary: keys are strings, values are float.

Example:

A = {'a':1, 'b':2, 'c':2, 'd':0}

I'd like to get 'b' or 'c' as answer with equal probability. I found a way to get said behaviour. However I'm not convinced this is best practice.

import random

A = {'a':1, 'b':2, 'c':2, 'd':0}
all = (A.items())
values = [(x[1],random.random(),x[0]) for x in all]
maxIndex = values.index(max(values))
print(values[maxIndex][2])

Is there a better (or even more elegant) approach?

like image 745
Dennis Klopfer Avatar asked Oct 28 '25 16:10

Dennis Klopfer


1 Answers

Try this:

import random
A = {'a':1, 'b':2, 'c':2, 'd':0}

mv = max(A.values())
random.choice([k for (k, v) in A.items() if v == mv])
=> 'b' # or 'c'

First, we find the maximum value and then we randomly pick one of the keys that match that value. We're using random.choice, which guarantees a random selection with uniform distribution.

like image 115
Óscar López Avatar answered Oct 31 '25 05:10

Óscar López



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!