Search code examples
pythonjsondictionarynestedenumerate

For loop enumerate. Python


Right now I have a JSON with a list containing two dictionaries. This code allows the user to search through the list via index number, retrieving a dictionary. Currently I get two printed results one for each dictionary, for example if I typed the index number 1, I get: No Index Number and then dictionary one printed out. Instead of this I would like to get only one result printed either the found dictionary or 1 error. Should I not use enumerate?

Here is my JSON(questions) containing a list of 2 dicts.

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

Here is my code

f = open('question.txt', 'r')
questions = json.load(f)
f.close()


value = inputSomething('Enter Index number: ')



for index, question_dict in enumerate(questions):

   if index == int(value):
      print(index, ') ', question_dict['question'],
         '\nCorrect:', question_dict['answer'],
         '\nIncorrect:', question_dict['wrong1'],
         '\nIncorrect:', question_dict['wrong2'],
         '\nIncorrect:', question_dict['wrong3'])
      break

   if not index == int(value):
      print('No index exists')

Solution

  • # Use `with` to make sure the file is closed properly
    with open('question.txt', 'r') as f:
        questions = json.load(f)
    
    value = inputSomething('Enter Index number: ')
    queried_index = int(value)
    
    # Since `questions` is a list, why don't you just *index` it with the input value
    if 0 <= queried_index < len(questions):
        question_dict = questions[queried_index]
        # Let `print` take care of the `\n` for you
        print(index, ') ', question_dict['question'])
        print('Correct:', question_dict['answer'])
        print('Incorrect:', question_dict['wrong1'])
        print('Incorrect:', question_dict['wrong2'])
        print('Incorrect:', question_dict['wrong3'])
    else:
        print('No index exists')