I recently started with LPTHW. At exercise 39 I did a litle sidetracked and updated the code towards my ideas. It works as intended except it picks the item out of countries in order and I'd like if it would do in random.
Can I solve this easily or the whole thing is a dead end? The idea is to pick a random element ask 1 of the 3 questions by random then compare if the answer is correct or not.
CodePudding user response:
You can use:
random.choice(list(my_dict.keys()))
To select a random key from a dictionary.
CodePudding user response:
Assuming that you want to loop over every item in your countries
dict as you do at the moment, just in a random order instead, then you can use random.shuffle
to randomly shuffle a list.
So, one option would be to extract the keys of your dictionary into a list, shuffle them, and iterate over those to provide the randomness.
Try replacing line 63 with these four lines of code instead:
country_keys = list(countries.keys())
random.shuffle(country_keys)
for country in country_keys:
abbrev = countries[country]