0

How could I print each question from the dictionary randomly without repeating?

Every time I run this command, I get repeated questions.

import random

capitals = {
    "Canada": "Toronto",
    "Spain": "Madrid",
    "Germany": "Berlin",
    "Belgium": "Brussels",
    "Australia": "Sydney",
}

for country, capital in capitals.items():
    country = random.choice(list(capitals.keys()))

    capital = capitals[country]
    question = input(f"What is the capital of {country}? : ")
    if question == capital:
        print("Congratulations!\n")

    else:
        print(f"Wrong! The correct answer: {capital}\n")
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Gabriel
  • 17
  • 2

1 Answers1

0

the problem with your code is that you called random.choice(list(capitals.keys())) 5 times and since every call is independent you got the same value more than once and didn't get at all some of the other values

in my code, I shuffled a list of your keys and then iterated over it , and since it was shuffled i picked different (random) country each time

this should do the trick :

import random

capitals = {
    "Canada": "Toronto",
    "Spain": "Madrid",
    "Germany": "Berlin",
    "Belgium": "Brussels",
    "Australia": "Sydney",
}
shuffeled_keys = list(capitals.keys())
random.shuffle(shuffeled_keys)
for country in shuffeled_keys:
    capital = capitals[country]
    question = input(f"What is the capital of {country}? : ")
    if question == capital:
        print("Congratulations!\n")
    else:
        print(f"Wrong! The correct answer: {capital}\n")

If you have any questions about y code feel free to ask me in the comments, and if my comment helped you please consider marking it as the answer :)

Ohad Sharet
  • 1,097
  • 9
  • 15
  • I appreciate your comment but the result is the same. I ran your code in VS Code and the result printed Australia twice and Germany did not appear – Gabriel Aug 06 '22 at 18:03
  • are you sure? I just tried it 3 times and it worked fine, could you try running my code as it is without changing it? (i don't know if you did but just in case :) ) and if it ends up working, could you mark my comment as the answer? – Ohad Sharet Aug 06 '22 at 18:05
  • you could add `print(shuffeled_keys)` before the for loop to see the order of the countries you are going to get – Ohad Sharet Aug 06 '22 at 18:21
  • I tried it a few times and it worked. I probably made some mistakes the first time. Thanks ! – Gabriel Aug 07 '22 at 01:54