1

Let's say i have a dict

{'option one': 5.0, 'option two': 5.0, 'option three': 10.0}

How can i randomly select a key based on the probabilities above (ie. option one and two will have a 25% of being chosen. Option 3 would have a 50% chance of being chosen)

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64
Ben Arnao
  • 492
  • 5
  • 11

1 Answers1

1

As a one liner:

import random

random.seed(100)
d = {'option one': 5.0, 'option two': 5.0, 'option three': 10.0}
picked = random.choices(*zip(*d.items()))[0]
print(picked)
# option one

More broken down:

import random

random.seed(100)
d = {'option one': 5.0, 'option two': 5.0, 'option three': 10.0}
# Key-value pairs in dictionary
items = d.items()
# "Transpose" items: from key-value pairs to sequence of keys and sequence of values
values, weights = zip(*items)
# Weighted choice (of one element)
picked = random.choices(values, weights)[0]
print(picked)
# option one

Note random.choices (which, unlike random.choice, offers a weights parameter) was added on Python 3.6.

jdehesa
  • 58,456
  • 7
  • 77
  • 121