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

Example: 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])])

Tags:

Misc Example