Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to attach a 3rd value in Python dictionaries?

This may be a stupid question, and I believe there is a good chance I am taking the completely wrong approach to solving my problem, so if anyone knows a better way, please feel free to correct me / point me in the right direction.

I'm trying to make a basic quiz program in Python for fun and I can't seem to find a good way to actually both call the questions with their answers AND store what the correct answer should be. Ideally I'd like to shuffle the answers within the question around as well so for example the answer to #1 is not always "A" as well, but that's going a step too far at the moment.

Anyway, I figured a dictionary could work. I'd do something like this:

test = {
    '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
    }

answer = raw_input(test['1'])

Which I could use to easily print out questions either in order or randomly with a little modification. However, I have no way of actually attaching the correct answer to the dictionary which means I'd have to do something like make ridiculous amounts of if statements. Does anyone know a solution? Is there a way to add a 3rd value to each dictionary entry? A work-around I'm completely overlooking? Any help would be greatly appreciated.

like image 425
Vale Avatar asked Dec 08 '22 04:12

Vale


1 Answers

It looks like you're laying out your data structure wrong. Instead of a dictionary of tuples or lists as your other answers are suggesting, you SHOULD be using a list of dictionaries.

questions = [
    {'question':"What is 1+1?\nA) 2\nB) 11\nC) 1\nD) None of the above.\n\n",
     'answer':"#A"},
    {'question':"What is 2+2?\nA) 2\nB) 4\nC) 1\nD) None of the above.\n\n",
     'answer':"#B"},
    ...}

This will let you iterate through your questions with:

for q in questions:
    print(q['question'])
    ans = input(">> ")
    if ans == q['answer']:
        # correct!
    else:
        # wrong!

If you still need numbers, you could either save number as another key of the dictionary (making this kind of like rows in a database, with number being the primary key):

{'number': 1,
 'question': ...,
 'answer': ...}

Or just iterate through your questions using enumerate with the start keyword argument

for q_num, q in enumerate(questions, start=1):
    print("{}. {}".format(q_num, q['question']))
    ...
like image 192
Adam Smith Avatar answered Dec 11 '22 11:12

Adam Smith