Reputation: 1033
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?
Upvotes: 1
Views: 1922
Reputation: 16309
random.shuffle
is not compatible with a dictionary. Try shuffling the keys only, then re-indexing the dictionary.
newvals = quizBank.values()
random.shuffle(newvals)
randBank = dict((idx, val) for idx, val in enumerate(newvals))
Upvotes: 2
Reputation: 77337
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.
Upvotes: 2
Reputation: 1936
You don't have a list of dictionaries - you have a dictionary of lists. Python is trying to use the standard methods to retrieve items in the list by using the bracket notation to get the item corresponding to the first index (0), but it fails because that's not a key in your dictionary.
As an interesting side note, if you make your keys all integers ranging from 0 to length-1, it won't crash!
Upvotes: 0