4

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?

Dennis Klopfer
  • 759
  • 4
  • 17
  • `random.choice(d.keys())` answered [here](https://stackoverflow.com/questions/4859292/how-to-get-a-random-value-in-python-dictionary) – Lex Jul 10 '17 at 00:56
  • 1
    @Lex this doesn't look like the same thing. It's like, first find the maximum value, and then choose a random key that maps to that value. – mwchase Jul 10 '17 at 00:58
  • @Jedi `A` is in this form. I'm not worried about O(n) as n=4 in this case. I'd be great to see a faster approach in general though. – Dennis Klopfer Jul 10 '17 at 01:18

1 Answers1

7

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386