
本教程详细阐述了如何使用python将多个长度不一的列表转换为特定的嵌套json结构。通过分析常见错误,文章重点介绍了itertools.batched(或其兼容实现)模块,结合zip和map函数,以声明式和高效的方式实现数据分组与转换,确保生成精确的层级化json输出,并兼顾python版本兼容性。
1. 场景概述与目标结构分析
在数据处理和API构建中,将扁平化的数据列表组织成具有层级关系的jsON对象是一种常见需求。本教程将以一个具体场景为例:给定三个Python列表——filtered_headings(主标题)、sub_headings(子标题)和values(对应值),我们的目标是生成一个具有特定嵌套结构的json对象。
输入数据示例:
filtered_headings = ['Educational Institutions', 'Number of students', 'Number of teaching staffs', 'Number of non- teaching staffs'] sub_headings = ['College/University', 'Basic Level', 'Secondary Level', 'Secondary Level', 'College/University', 'Basic Level', 'Secondary Level', 'College/University', 'Basic Level', 'Basic Level', 'College/University', 'Secondary Level'] values = ['2', '10', '12', '566', '400', '799', '355', '115', '12', '115', '11', '11']
期望的JSON输出结构:
{ "Educational Institutions": { "College/University": "2", "Basic Level": "10", "Secondary Level": "12" }, "Number of students": { "Secondary Level": "566", "College/University": "400", "Basic level": "799" }, "Number of teaching staffs": { "Secondary Level": "355", "College/University": "115", "Basic Level": "12" }, "Number of non- teaching staffs": { "Basic Level": "115", "College/University": "11", "Secondary Level": "11" } }
从上述期望结构中可以看出,每个filtered_headings中的元素(如”Educational Institutions”)都将作为顶层JSON对象的键。其对应的值是一个子字典,该子字典
立即学习“Python免费学习笔记(深入)”;