You need to enable JavaScript to run this app. Python如何从字典列表中提取键值并按公共键分组生成列表字典
优惠活动
大模型
产品
解决方案
定价
更多

Python如何从字典列表中提取键值并按公共键分组生成列表字典

Python实现JSON按指定字段分组

实现思路

遍历JSON解析后的列表,以config字段的值为键,同组的id值追加到对应列表中即可。

代码实现

方法1:使用普通字典(无需额外导入依赖)

import json

# 解析输入JSON,若为本地JSON文件可改用 json.load(open("your_file.json", "r"))
input_data = json.loads('''
{
    "data": [
        {"config": "current", "id": "0"},
        {"config": "current", "id": "1"},
        {"config": "current", "id": "2"},
        {"config": "current", "id": "3"},
        {"config": "previous", "id": "4"},
        {"config": "previous", "id": "5"},
        {"config": "current", "id": "6"}
    ]
}
''')["data"]

result = {}
for item in input_data:
    config_key = item["config"]
    if config_key not in result:
        result[config_key] = []
    result[config_key].append(item["id"])

print(result)

方法2:使用collections.defaultdict简化写法

import json
from collections import defaultdict

input_data = json.loads('''
{
    "data": [
        {"config": "current", "id": "0"},
        {"config": "current", "id": "1"},
        {"config": "current", "id": "2"},
        {"config": "current", "id": "3"},
        {"config": "previous", "id": "4"},
        {"config": "previous", "id": "5"},
        {"config": "current", "id": "6"}
    ]
}
''')["data"]

result = defaultdict(list)
for item in input_data:
    result[item["config"]].append(item["id"])

# 转换为普通字典为可选操作,根据你的需求决定是否添加
result = dict(result)
print(result)

输出结果

两种方法运行后都会得到目标格式:

{'current': ['0', '1', '2', '3', '6'], 'previous': ['4', '5']}

内容的提问来源于stack exchange,提问作者Vishwanath S Manvi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 16:06:04