Answers for "how to pick a random dictionary key weighted by value with Python"

0

how to pick a random dictionary key weighted by value with Python

import random

# with float values (python3):
random.choices(list(dictionary.keys()), weights = dictionary.values(), k=1)[0]


# with integer values (python2):
# beware: as memory consuming as the total of values
dictionary = {
  'one chance over six' = 1,   # /(1+2+3)=1/6
  'one chance over three' = 2, # 2/(1+2+3)=1/3
  'one chance over two' = 3    # 3/(1+2+3)=1/2
}
random.choice([key for key in dictionary for i in range(dictionary[key])])
Posted by: Guest on December-08-2020

Code answers related to "how to pick a random dictionary key weighted by value with Python"

Python Answers by Framework

Browse Popular Code Answers by Language