1

So i have a dictionary with:

dict = {1:'hi', 2:'bye', 3:'who', 4:'which', 5:'where'}

and I'm trying to randomly extract 3 words from the dictionary and append into a list.

I tried:

import random
lst = []
pick = random.choice(lst.keys())

but I'm getting the error:

TypeError: 'dict_keys' object does not support indexing
Maxxx
  • 3,688
  • 6
  • 28
  • 55

1 Answers1

0
import random
dict = {1:'hi', 2:'bye', 3:'who', 4:'which', 5:'where'}
random.choice(list(dict .keys()))

nr,text= random.choice(list(dict .items()))

try this?

BEvilM
  • 43
  • 11
  • @Belgiumclub thanks, but what if i want to randomly extract 3 words instead of 1? – Maxxx May 15 '19 at 08:52
  • @Maxxx loop over the random choice and keep it in a list till you have 3 random answers if they need to be unique then filter it hope this helps :) – BEvilM May 15 '19 at 08:58
  • This is not correct: He can get double values in his result. He wrote "extract" which implies you can not make the same choice again. With your code it it possible to get ```['hi','hi','hi']``` as a result. – Frieder May 15 '19 at 08:59