I have a dictionary like this:
questions ={
'1.Who is Satoshi Nakamoto' : {'answers':{'right_answer':'Pseudonym','wrong_answer':['Bill Gate', 'Elon Musk', 'Warren Buffet']}},
'2.Who is richest' : {'answers':{'right_answer':'Pseudonym','wrong_answer':['Bill Gate', 'Elon Musk', 'Warren Buffet']}}
}
Based on the dictionary, I want to print the questions and the option values.
This is the code I used:
for question in q:
print(question)
answers =([questions[question]['answers']['right_answer']] questions[question]['answers']['wrong_answer'])
for answer in answers:
print(answer)
This produces a result like:
1.Who is Satoshi Nakamoto
Pseudonym
Bill Gate
Elon Musk
Warren Buffet
2.Who is richer
Pseudonym
Bill Gate
Elon Musk
Warren Buffet
But I want to print the options with bullet headers A, B, C, D, etc. like this:
1.Who is Satoshi Nakamoto
A.Pseudonym
B.Bill Gate
C.Elon Musk
D.Warren Buffet
2.Who is richer
A.Pseudonym
B.Bill Gate
C.Elon Musk
D.Warren Buffet
Maybe someone could help me this. Thank you so much!
CodePudding user response:
You want to use the string
library's ascii uppercase and zip()
to enumerate your answers:
import string
answers = ['Pseudonym', 'Bill Gate', 'Elon Musk', 'Warren Buffet']
for bullet, answer in zip(string.ascii_uppercase, answers):
print(f"{bullet}. {answer}")
zip()
will take some number of lists (or other collections) and group the first element of each collection, then the second, then the third and so on. So, zip([1,2,3], ['a','b','c'])
will give you [(1, 'a'), (2, 'b'), (3, 'c')]
. Then, your for
loop unpacks each of these tuples and makes them available for the print statement's f-string.
This produces the following result:
>>> answers = ['Pseudonym', 'Bill Gate', 'Elon Musk', 'Warren Buffet']
>>> for bullet, answer in zip(string.ascii_uppercase, answers):
... print(f"{bullet}. {answer}")
...
A. Pseudonym
B. Bill Gate
C. Elon Musk
D. Warren Buffet
CodePudding user response:
I redesigned the structure of questions
because I don't think it's good. Making questions
a list allows us to shuffle the questions so that they don't always come in the same order. I shuffled the answers too, so that the correct answer won't always be in the first position.
import random
import string
questions = [
{'question': 'Who is Satoshi Nakamoto',
'right_answer': 'Pseudonym',
'wrong_answers': ['Bill Gate', 'Elon Musk', 'Warren Buffet']},
{'question': 'Who is richest',
'right_answer': 'Pseudonym',
'wrong_answers': ['Bill Gates', 'Elon Musk', 'Warren Buffet']}]
random.shuffle(questions)
for i, entry in enumerate(questions, start=1):
all_answers = entry['wrong_answers'] [entry['right_answer']]
random.shuffle(all_answers)
print(f'{i}. {entry["question"]}')
for letter, answer in zip(string.ascii_uppercase, all_answers):
print(f' {letter}. {answer}')
A possible result:
1. Who is richest
A. Pseudonym
B. Warren Buffet
C. Bill Gates
D. Elon Musk
2. Who is Satoshi Nakamoto
A. Elon Musk
B. Pseudonym
C. Warren Buffet
D. Bill Gate