从嵌套在lis中的词典中阅读

2024-04-24 15:01:12 发布

您现在位置:Python中文网/ 问答频道 /正文

[
    {
        "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中的“question”和列表2中的question。你知道吗

代码如下:

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)

Tags: 文件answerjson列表questionsquestionprintvalueerror