0

I have a dictionary:

categories = {
    "fruits" = ['banana', 'apple', 'strawberry', 'grape', 'watermelon', 'mango'],
    "countries" = ['Canada', 'Brazil', 'Ghana', 'Cuba', 'Japan', 'Germany', 'France'],
    "colors" = ['green', 'brown', 'pink', 'yellow', 'red', 'grey', 'blue']
    }

And I need a function that returns a category/key (like 'colors') and 3 different words from one single key/category (like 'brown', 'pink', 'yellow'). So I wrote:

category = random.choice(list(categories))
print(category)
words = random.choice(categories[category]), random.choice(categories[category]), random.choice(categories[category])
print(words)

But sometimes it returns the same words. For example:

colors
('brown', 'blue', 'blue')

What can I do to make sure it will always return me 3 different words?

  • 2
    Try to explore `random.sample()`? – Daniel Hao Jun 17 '22 at 17:15
  • Repeatedly calling `random.choice()` is not the right thing to do - each call is unaware of the previous ones. You have `random.choices()` if you want repetitions, and `random.sample()` if you don't. – gimix Jun 17 '22 at 17:22

1 Answers1

0

Put the second block of code inside a loop and then add the following statement at the end of the loop

if colors==set(colors):
   break
Stalk4r
  • 26
  • 4