Python如何将二维列表转换为指定结构的字典格式数据
Python二维列表转指定字典列表实现方法
核心逻辑:遍历原始二维列表的每个子项,取出子列表中存储的问题字符串,包装为键名是question的字典,最终汇总为新列表即可。
完整代码实现
转换全部条目
如果需要把原始列表里的所有问题都转为目标格式,用列表推导式一行就能完成:
# 原始二维列表,注意不要用list作为变量名,会覆盖Python内置类型 raw_questions = [['What did the Vedas contain large collections of?'], ['What did the Vedas contain large collections of?'], ['What was accompanied by the rise of ascetic movements in Greater Magadha?'], ['In what part of India did Wootz steel originate?'], ['What country was ruled by dynasties during the Classical period?']] # 格式转换 result = [{"question": single_question[0]} for single_question in raw_questions]
匹配示例输出(仅取前3条)
你给出的示例输出只保留了前3个问题,只需要对原始列表做切片取前3项再转换即可:
result = [{"question": single_question[0]} for single_question in raw_questions[:3]]
运行上述代码后得到的result和你给出的示例输出完全一致:
[{'question': 'What did the Vedas contain large collections of?'}, {'question': 'What did the Vedas contain large collections of?'}, {'question': 'What was accompanied by the rise of ascetic movements in Greater Magadha?'}]
代码说明
- 原始列表的每个元素都是长度为1的子列表,
single_question[0]就是子列表里存储的问题文本 - 列表推导式会遍历每一个子列表,自动组装成要求的字典结构,比普通for循环写法更简洁高效
- 不要使用
list、dict作为自定义变量名,否则会覆盖Python内置的列表、字典类型,导致后续调用内置方法时报错。
内容的提问来源于stack exchange,提问作者Roshni Hirani
相关产品推荐
相关产品推荐

