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

Solutions on MaxInterview for how to pick a random dictionary key weighted by value with python by the best coders in the world

showing results for - "how to pick a random dictionary key weighted by value with python"
Alois
05 Nov 2018
1import random
2
3# with float values (python3):
4random.choices(list(dictionary.keys()), weights = dictionary.values(), k=1)[0]
5
6
7# with integer values (python2):
8# beware: as memory consuming as the total of values
9dictionary = {
10  'one chance over six' = 1,   # /(1+2+3)=1/6
11  'one chance over three' = 2, # 2/(1+2+3)=1/3
12  'one chance over two' = 3    # 3/(1+2+3)=1/2
13}
14random.choice([key for key in dictionary for i in range(dictionary[key])])