这篇文章已被解析
如何在问题中引用topic
键?我想在我的列表中搜索具有特定主题的所有问题,然后返回关于随机问题的所有信息。
然而,当使用下面的代码时,我得到一个错误说:
if question['topic'] == topic:
TypeError: 'int' object is not subscriptable
然而,如果我尝试将整数更改为字符串,我得到一个错误,说它们必须是整数。怎么解呢?
代码-这段代码应该将特定主题的所有问题添加到列表中,以便我可以在列表中使用随机函数来生成随机问题。
def random_question_in_topic(topic: str):
topic_questions = []
for question in questions:
if question['topic'] == topic:
topic_questions.append(question)
print(topic_questions)
提取从我的字典。(共30项)
questions = {
1 : {
'type': 'memory',
"topic": "literature",
"question": "Who wrote Twilight series of novels?",
"answer": "stephenie meyer",
},
2 : {
'type': 'memory',
"topic": "literature",
"question": "What was Frankenstein's first name?",
"answer": "jolly roger",
},
3 : {
'type': 'memory',
"topic": "general",
"question": "What is the only anagram of the word 'english'?",
"answer": "shingles",
},
4 : {
'type': 'memory',
"topic": "general",
"question": "Gala, Jonagold and Pink Lady are varieties of which fruit?",
"answer": "apple",
}
}
提前感谢!
我使用Python 3.8.12在Replit上。
for question in questions.values():
if question['topic'] == 'history':
print(question)
topic_questions.append(question)
感谢原帖的评论。
出现此错误是因为当您遍历字典时,您正在遍历它的键。让我们仔细看看。
如果运行以下代码
for question in questions:
print(question)
…您将得到以下输出:
1
2
3
4
所以,与其遍历键,不如遍历字典的值。为此,您可以使用dict
对象的values()
方法。因此,如果您尝试以下代码:
for question in questions.values():
print(question)
…您将得到如下输出:
{'type': 'memory', 'topic': 'literature', 'question': 'Who wrote Twilight series of novels?', 'answer': 'stephenie meyer'}
...
现在,变量question
是一个对象,您可以对其使用索引,例如question['topic']
。因此,代码可以重写为:
def random_question_in_topic(topic: str):
topic_questions = []
for question in questions.values():
if question['topic'] == topic:
topic_questions.append(question)
print(topic_questions)