【问题标题】:Reading from dictionaries nested in a list从嵌套在列表中的字典中读取
【发布时间】:2015-05-19 14:04:18
【问题描述】:
[
    {
        "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() 来执行此操作,唯一的事情是它在“问题”中列出字符串的每个字符,而不是从列表 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)

【问题讨论】:

    标签: python list dictionary nested enumerate


    【解决方案1】:

    您有 一个 列表,其中包含两个字典。只需遍历列表并为每个字典提取 question 键:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多