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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With