You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何快速实现Python嵌套字典到指定列表结构的转换?

Python嵌套字典转列表结构的快速实现

你可以利用列表推导式结合字典解包语法快速完成转换,无需手动逐个构建每个列表元素,代码简洁高效:

输入字典

input_dict = {
    "demographicAll": {
        "allAges": {
            "rating": "8.8",
            "votes": "2327099"
        },
        "agesUnder18": {
            "rating": "9.0",
            "votes": "1050"
        },
        "ages18To29": {
            "rating": "9.0",
            "votes": "363089"
        },
        "ages30To44": {
            "rating": "8.8",
            "votes": "914737"
        },
        "agesOver45": {
            "rating": "8.2",
            "votes": "182612"
        }
    }
}

转换代码

output_dict = {
    "demographicAll": [
        {"ageRange": age, **data} for age, data in input_dict["demographicAll"].items()
    ]
}

代码说明

  • 列表推导式遍历input_dict["demographicAll"]的所有键值对(age是年龄区间键名,data是对应的评分、投票字典)
  • 用{"ageRange": age, **data}生成每个列表元素:ageRange字段对应原键名,**data直接解包原字典中的rating和votes字段,无需手动逐个添加

验证输出

如果需要格式化打印结果,可以用json模块:

import json
print(json.dumps(output_dict, indent=4))

输出结果完全符合目标结构:

{
    "demographicAll": [
        {
            "ageRange": "allAges",
            "rating": "8.8",
            "votes": "2327099"
        },
        {
            "ageRange": "agesUnder18",
            "rating": "9.0",
            "votes": "1050"
        },
        {
            "ageRange": "ages18To29",
            "rating": "9.0",
            "votes": "363089"
        },
        {
            "ageRange": "ages30To44",
            "rating": "8.8",
            "votes": "914737"
        },
        {
            "ageRange": "agesOver45",
            "rating": "8.2",
            "votes": "182612"
        }
    ]
}

内容的提问来源于stack exchange,提问作者rizerkrof

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 12:10:38