jeudi 9 septembre 2021

Randomly selecting a word from a dictionary with a given probability [duplicate]

I have a dictionary that has words and their probabilities of being selected as below:

dic = {'A': 0.2, 'B': 0.45, 'C': 0.35}

I want to randomly select 1 word based on its associated probability. So 'B' being selected would have highest probability. I've tried to use random.choice and random.choices but it isn't working. This is what I've tried:

next_word = random.choices(dic.keys(), weights=dic.values(), k=1)

I get TypeError: 'dict_keys' object is not subscriptable

Please suggest how I can do this.




Aucun commentaire:

Enregistrer un commentaire