-1

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.

amnesic
  • 259
  • 1
  • 7

2 Answers2

2
import random
dic = {'A': 0.2, 'B': 0.45, 'C': 0.35}
next_word = random.choices(list(dic.keys()), weights=list(dic.values()), k=1)
next_word
Thomas Kimber
  • 10,601
  • 3
  • 25
  • 42
0

You are definitely on the right track. But you can do this to make it right:

next_word = random.choices(list(dic.keys()), weights=dic.values(), k=1)[0]
Dharman
  • 30,962
  • 25
  • 85
  • 135
Coder Alpha
  • 157
  • 1
  • 10