
本教程详细阐述了如何使用python将多个长度不一的列表转换为特定的嵌套json结构。通过分析常见错误,文章重点介绍了itertools.batched(或其兼容实现)模块,结合zip和map函数,以声明式和高效的方式实现数据分组与转换,确保生成精确的层级化json输出,并兼顾python版本兼容性。
在数据处理和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免费学习笔记(深入)”;
以上就是Python中利用itertools高效构建复杂嵌套JSON结构的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号