Search code examples
pythonlistdictionarynestedenumerate

Reading from dictionaries nested in a list


[
    {
        "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"
    }
]

Currently I have a file that loads a JSON file (above) that is filled with two lists. Each of those items is a dictionary consisting of 5 items.

I am trying to list "question" from both lists along with its index. Right now I am using enumerate() to do this, the only thing is that it is listing each character of the string in "question" rather than listing "question" from list 1 and question from list 2.

Here is the code:

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)

Solution

  • You have one list, with two dictionaries. Just loop over the list and extract the question key for each dictionary:

    for i, question_dict in enumerate(questions):
        print(i, question_dict['question'])