请有人告诉我如何访问此类键值对。我想访问“类别”,“问题”,“正确答案”,“错误答案”。我可以删除“响应代码”和“结果”,并且只使用列表中的嵌套字典,但我想尝试不操作数据。我知道将使用 for 循环。
question_data = {"response_code": 0,
"results": [
{"type": "multiple",
"difficulty": "medium",
"category": "Entertainment: Film",
"question": "Sign of death.",
"correct_answer": "Red Shirt",
"incorrect_answers": ["Minions", "Expendables", "Cannon Fodder"]
}
]
在示例中尝试一下:
代码:
import random
import string
QUESTIONS = {
"What is the name of PEP 572?": [
"Assignment Expressions",
"Named Expressions",
"The Walrus Operator",
"The Colon Equals Operator",
],
"Which one of these is an invalid use of the walrus operator?": [
"[y**2 for x in range(10) if y := f(x) > 0]",
"print(y := f(x))",
"(y := f(x))",
"any((y := f(x)) for x in range(10))",
],
}
num_correct = 0
for question, answers in QUESTIONS.items(0):
correct = answers[0]
random.shuffle(answers)
coded_answers = dict(zip(string.ascii_lowercase, answers))
valid_answers = sorted(coded_answers.keys())
for code, answer in coded_answers.items():
print(f" {code}) {answer}")
while (user_answer := input(f"\n{question} ")) not in valid_answers:
print(f"Please answer one of {', '.join(valid_answers)}")
if coded_answers[user_answer] == correct:
print(f"Correct, the answer is {user_answer!r}\n")
num_correct += 1
else:
print(f"No, the answer is {correct!r}\n")
print(f"You got {num_correct} correct out of {len(QUESTIONS)} questions")