Quick question, I'm trying to display random questions in a simple quiz program using a list of dictionaries. I found a way to do this, but it was fairly drawn out and buggy so I decided it would be much easier to iterate through the questions instead after shuffling them once at the start.
I stumbled across random.shuffle()
which seems to be just what I want, however, I can't seem to get it to work. Here's what I'm currently trying:
import random
quizBank = {
1: ["What is 1+1?\nA) 2\nB) 11\nC) 1\nD) None of the above.\n\n",'A'],
2: ["What is 2+2?\nA) 2\nB) 4\nC) 1\nD) None of the above.\n\n",'B'],
3: ["What is 3+3?\nA) 2\nB) 11\nC) 6\nD) None of the above.\n\n",'C'],
4: ["What is 4+4?\nA) 2\nB) 11\nC) 1\nD) None of the above.\n\n",'D'],
5: ["What is 5+5?\nA) 2\nB) 11\nC) 10\nD) None of the above.\n\n",'C'],
6: ["What is 6+6?\nA) 2\nB) 12\nC) 1\nD) None of the above.\n\n",'B'],
}
random.shuffle(quizBank)
print(quizBank)
Which results in the following error:
Traceback (most recent call last):
File "C:\Users\MyUserName\Desktop\test.py", line 12, in <module>
random.shuffle(quizBank)
File "C:\Python27\lib\random.py", line 291, in shuffle
x[i], x[j] = x[j], x[i]
KeyError: 0
Does anyone know what I am doing wrong and can give me a point in the right direction?
The answer I already gave you is good. You could also shuffle the values:
values = quizBank.values()
random.shuffle(values)
One of the reasons that I suggested not using a dict is that once you shuffle, the indexes you setup are shuffled too.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments