[
{
"wrong3": "Nope, also wrong",
"question": "Example Question 1",
"wrong1": "Incorrect answer",
"wrong2": "Another wrong one",
"answer": "Correct answer"
},
{
"wrong3": "0",
"question": "How many good Matrix movies are there?",
"wrong1": "2",
"wrong2": "3",
"answer": "1"
}
]
目前我有一个加载JSON文件的文件(上面),里面有两个列表。每个项目都是由5个项目组成的字典。
我想列出"问题"来自两个列表及其索引。现在我正在使用enumerate()
执行此操作,唯一的事情是它列出了字符串中的每个字符" question"而不是列出"问题"从列表1和列表2的问题。
以下是代码:
import json
try:
f = open('question.txt', 'r')
questions = json.load(f)
f.close()
except FileNotFoundError:
print('NotFoundError \n')
questions = {}
except ValueError:
print('ValueError \n')
questions = {}
except NameError:
print('NameError \n')
questions = {}
for i, v in enumerate(questions[0]['question']):
print (i,v)
答案 0 :(得分:6)
您有一个列表,其中包含两个词典。只需循环遍历列表并提取每个字典的question
键:
for i, question_dict in enumerate(questions):
print(i, question_dict['question'])