在python中将三个长度不均匀的列表转换为JSON

问题描述 投票:0回答:2

我有 3 个清单:

filtered_headings = ['教育机构','学生人数','教职人员人数','非教学人员人数']

sub_headings = ['学院/大学', '基础水平', '中学水平', '中学水平', '学院/大学', '基础水平', '中学水平', '学院/大学', '基础级别'、'基础级别'、'学院/大学'、'中学级别']

值 = ['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"
 }
}

我得到以下输出:

{
 "Educational Institutions": {
  "College/University": "11",
  "Basic Level": "115",
  "Secondary Level": "11"
 },
 "Number of students": {
  "College/University": "11",
  "Basic Level": "115",
  "Secondary Level": "11"
 },
 "Number of teaching staffs": {
  "College/University": "11",
  "Basic Level": "115",
  "Secondary Level": "11"
 },
 "Number of non- teaching staffs": {
  "College/University": "11",
  "Basic Level": "115",
  "Secondary Level": "11"
 }
}

它一遍又一遍地重复最后3个值,我如何获得预期格式的输出?

我的代码是:

result = {}
for indv_heading in filtered_headings:
    data_dict = {sub_heading: value for sub_heading,
                 value in zip(sub_headings, values)}
    result[indv_heading] = data_dict
# print(result)
json_data = json.dumps(result, indent=1)
print(json_data)
python json list
2个回答
0
投票

您可以将

sub_headings
values
压缩成对,并使用
itertools.batched
将它们分成 3 个一组以构造子字典,然后将
sub_headings
与子字典一起压缩以生成键值字典的顺序:

from itertools import batched
dict(zip(filtered_headings, map(dict, batched(zip(sub_headings, values), 3))))

itertools.batched
是在 Python 3.12 中引入的。如果您使用的是早期的 Python 版本,则可以使用
batched
配方。


0
投票

我不确定列表的长度将来是否会增加,如果不会,我们可以获得一个不适合生产的解决方案,但可以是简单、可读和可理解的。

简单的未优化解决方案:

result = {}
for header in filtered_headings:
    pre = {}
    for i in range(3):
        pre[sub_headings.pop(0)] = values.pop(0)
    result[header] = pre
json_data = json.dumps(result, indent=1)
print(json_data)

另外,您可以告诉我们您的数据是从哪里获取的吗?

因为也许有更有效的方法来做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.