Home > Net >  I need help making a program that will take random values of a dictionary and put them in another
I need help making a program that will take random values of a dictionary and put them in another

Time:05-12

This is meant for quiz I am trying to program in python. I have no ideas on how to proceed with this part of my program, since I'm fairly new to programming, but essentially I'm trying to set the key values of dico_q_ran to the values taken randomly from q_bank.

q_bank = {1 : {
        "question" : "",
        "answer" : ""
    },
    2 : {
        "question" : "",
        "answer" : ""
    },
    3 : {
        "question" : "",
        "answer" : ""}
    etc...
    25 : {
        "question" : "",
        "answer" : ""}

dico_q_ran = {0, 1 , 2, ...., 10}

for i in range(1, 11):
    key_rand = (random.randrange(0,26))
    dico_q_alea[i] = banque_de_questions[key_rand]

Sorry if the naming is a bit weird, I did light translation of the names from french so it would make a bit more sense for english speakers.

CodePudding user response:

There are few problems here. Firstly, dico_q_ran is defined as a set, not a dict, so dico_q_alea[i] assignment is not possible. If you want it to be a dict, just init it empty as dico_q_ran = {}. I'd consider using lists instead, though.

Secondly, I'd suggest using lists for both q_bank and dico_q_ran, since your keys are sequential numbers, and that's what lists are for:

q_bank = [
    {
        "question": "...",
        "answer": "...",
    },
}

That will also help you fix another problem more easily. Current randomization doesn't guarantee that the same question won't be used twice. With lists it's getting as simple as:

dico_q_alea = random.sample(q_bank, 10)
  • Related